简体   繁体   English

搜索列表中的元素是否在其他列表中至少包含一次

[英]Search if elements from list are contained at least once in other list

I have two list of strings 我有两个字符串列表

a = ['a','b','c']
b = ['aa','b','d']

I need to check if every element from list a is included in any element in list b 我需要检查列表a中的每个元素是否包含在列表b中的任何元素中

I tried couple of solutions, but below one I thought should work, but it always returning True 我尝试了几种解决方案,但我认为应该可以解决,但总是返回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))

Anyone has any idea ? 有人有什么主意吗?

I need that comparison for searching keywords in query files. 我需要该比较来搜索查询文件中的关键字。 I'm searching if all keywords are in file (file is split into lines as list) and if yes then return all lines containing any of the keyword. 我正在搜索是否所有关键字都在文件中(文件作为列表分为几行),如果是,则返回包含任何关键字的所有行。

You can use any and all like this 你可以使用anyall这样

>>> 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))

Finds words usage in lines. 查找行中的单词用法。 Word can be a substring of line (line can contain multiple words). 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)

Output of example: 示例输出:

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.

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