2017-05-16 44 views
0
strings = ("name", "last", "middle") 
file = ["name","blabla","middle"] 
for line in file: 
    if any(s in line for s in strings): 
     print ("found") 

我想比较两个列表,并得到检查的常见字符串,当且仅当两个或两个以上字符串是相同的。 上面的代码适用于一个但我希望它检查两个关键字。Python的比较两份名单,并检查了两个独特的字符串

如:应该只有print(found)如果且仅当“名”和“中间”被发现。不仅如果找到'名字'。它应该检查两个字符串。

+0

你有你的元组或列表重复值?你想如何处理不同大小写的字符串? – styvane

回答

0

首先,你可以找到使用list comprehension匹配的号码,然后len > 2或不

>>> num = 2 
>>> l = [i for i in strings if i in file] 
>>> if len(l) >= num: 
     print('found') 
found 
0

如果你喜欢的俏皮话,这里是我的命题:

# If two or more elemnts from listA are present in listB returns TRUE 
def two_or_more(listA, listB): 
    return sum(map(lambda x : x in listB, listA)) > 1 
2

您可以使用set S和intersection如果你想检查一下共同的物品(这不是重要的)。

if len(set(strings).intersection(file)) >= 2: # at least 2 common values 
    print('found') 

如果您想寻找固定的项目,你可以使用issubset方法:

strings = ("name", "last", "middle") 
file = ["name","blabla","middle"] 

check = {'name', 'middle'} # that's a set containing the items to look for. 
if check.issubset(strings) and check.issubset(file): 
    print('found')