[英]Search if elements from list are contained at least once in other list
我有两个字符串列表
a = ['a','b','c']
b = ['aa','b','d']
我需要检查列表a中的每个元素是否包含在列表b中的任何元素中
我尝试了几种解决方案,但我认为应该可以解决,但总是返回True
def list_compare(list1,list2):
for item in list1:
if any(item for s in list2):
return True
return False
print(list_compare(a,b))
有人有什么主意吗?
我需要该比较来搜索查询文件中的关键字。 我正在搜索是否所有关键字都在文件中(文件作为列表分为几行),如果是,则返回包含任何关键字的所有行。
你可以使用any
和all
这样
>>> def list_compare(list1,list2):
... return all(any(x in y for y in list2) for x in list1)
...
>>> print(list_compare(a,b))
False
def compare(list1,list2):
for item in list1:
if item in list2: #checking the item is present in list2
continue # if yes, goes for next item in list1 to check
else:
return False #if no, immediately comes out with "False"
else:
return True #reaches here, only if all the items in list1 is
#present in list2 , returning "True"
print(compare(lista,listb))
查找行中的单词用法。 Word可以是line的子字符串 (line可以包含多个单词)。
wordsToFind = ['a','b','c']
linesOfDocument = ['aa','ab','1234b','d']
for word in wordsToFind:
for line in linesOfDocument:
if word in line:
print('Found word ' + word + ' in line ' + line)
示例输出:
Found word a in line aa
Found word a in line ab
Found word b in line ab
Found word b in line 1234b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.