问题:检查项目是否在数组/列表中

如果我有一个字符串数组,是否可以检查字符串是否在数组中而不进行for循环?具体来说,我正在寻找一种在if语句中执行此操作的方法,因此如下所示:

if [check that item is in array]:

If I’ve got an array of strings, can I check to see if a string is in the array without doing a for loop? Specifically, I’m looking for a way to do it within an if statement, so something like this:

if [check that item is in array]:

回答 0

假设您说“列表”的意思是“数组”,那么您可以

if item in my_list:
    # whatever

这适用于任何集合,而不仅仅是列表。对于字典,它将检查字典中是否存在给定的键。

Assuming you mean “list” where you say “array”, you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.


回答 1

我还要假设您说“数组”时的意思是“列表”。Sven Marnach的解决方案很好。如果要对列表进行重复检查,则可能有必要将其转换为集合或冻结集,这对于每次检查来说可能更快。假设您的str列表称为subjects

subject_set = frozenset(subjects)
if query in subject_set:
    # whatever

I’m also going to assume that you mean “list” when you say “array.” Sven Marnach’s solution is good. If you are going to be doing repeated checks on the list, then it might be worth converting it to a set or frozenset, which can be faster for each check. Assuming your list of strs is called subjects:

subject_set = frozenset(subjects)
if query in subject_set:
    # whatever

回答 2

使用lambda函数。

假设您有一个数组:

nums = [0,1,5]

检查5是否在nums

(len(filter (lambda x : x == 5, nums)) > 0)

该解决方案更加强大。现在,您可以检查数组中是否有满足特定条件的任何数字nums

例如,检查是否存在大于或等于5的任何数字nums

(len(filter (lambda x : x >= 5, nums)) > 0)

Use a lambda function.

Let’s say you have an array:

nums = [0,1,5]

Check whether 5 is in nums in Python 3.X:

(len(list(filter (lambda x : x == 5, nums))) > 0)

Check whether 5 is in nums in Python 2.7:

(len(filter (lambda x : x == 5, nums)) > 0)

This solution is more robust. You can now check whether any number satisfying a certain condition is in your array nums.

For example, check whether any number that is greater than or equal to 5 exists in nums:

(len(filter (lambda x : x >= 5, nums)) > 0)

回答 3

您必须对数组使用.values。例如,假设您的数据框的列名称为test [‘Name’],则可以

if name in test['Name'].values :
   print(name)

对于普通列表,您不必使用.values

You have to use .values for arrays. for example say you have dataframe which has a column name ie, test[‘Name’], you can do

if name in test['Name'].values :
   print(name)

for a normal list you dont have to use .values


回答 4

您也可以对数组使用相同的语法。例如,在熊猫系列中搜索:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。