简体   繁体   English

在python中搜索一个以上字符串的列表

[英]Seaching a list for more than one string in python

I wrote the below function to return True if it detects the string 'Device' in a list 我写了下面的函数,如果它在列表中检测到字符串“ Device”,则返回True

def data_filter2(inner_list):
   return any(['Device' in str(x) for x in inner_list])

is there a way to search the list for more than one string and return True it it finds either one? 有没有一种方法可以在列表中搜索多个字符串并返回True(找到一个字符串)?

I tried 我试过了

def data_filter2(inner_list):
   return any(['Device' or 'Drug' in str(x) for x in inner_list])

But this did not work. 但这没有用。

You could use a binary operator or or and depending on what you intend, but slightly different from how you've done it: 您可以使用二进制运算符orand具体取决于您要使用的运算符,但与完成操作的方式略有不同:

def data_filter2(inner_list):
   return any('Device' in str(x) or 'Drug' in str(x) for x in inner_list)

You could use a generator expression, and avoid creating a new list for your check. 您可以使用生成器表达式,并避免为检查创建新列表。

What if you reverse the logic? 如果您颠倒逻辑该怎么办?

def data_filter2(inner_list):
   return any([str(x) in ['Device', 'Drug'] for x in inner_list])

This provides a framework that can "accept" more items to check for. 这提供了一个可以“接受”更多项目进行检查的框架。 Chaining or is not very pythonic to my eyes. 连锁or在我眼中不是很蟒蛇。

What is interesting to note here is the following: 这里有趣的是以下内容:

alist_ = ['drugs', '123123']
astring = 'drug'


for i in range(len(alist_)):
    print(astring in alist_[i])
print('-----')

print(astring in alist_)

#prints:
#True
#False
#-----
#False

What this says is that searching for a string in a list requires the strings to be identical (case sensitive) but searching for a string in a string allows for substrings to return True as well. 这表示在列表中搜索字符串要求字符串相同(区分大小写),但是在字符串中搜索字符串也允许子字符串返回True

The solutions using any and comprenhensions are nice. 使用any和comprehensions的解决方案都不错。 Another alternative would be to use set intersection. 另一种选择是使用集合交集。

In [30]: bool(set(['aaa', 'foo']) & set(['foo']))
Out[30]: True

In [31]: bool(set(['aaa', 'foo']) & set(['bar']))
Out[31]: False

You can do it in one line like so: 您可以像这样一行来完成:

def data_filter2(inner_list):
   return any([x in y for x in ['Device', 'Drug'] for y in inner_list])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM