Python 比较两个列表并检查两个唯一字符串
Python Compare two lists and check for two unique strings
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
for line in file:
if any(s in line for s in strings):
print ("found")
我想比较两个列表并检查公共字符串,当且仅当两个或多个 字符串相同时。
上面的代码适用于 one 但我希望它检查 two 关键字。
例如:它应该 只有 print(found)
如果 并且只有 'name' 和 'middle'被发现。不仅是 'name' 被发现。它应该检查 两个 个字符串。
首先,您可以使用 list comprehension
查找匹配项数量,然后使用 len > 2
或不使用
>>> num = 2
>>> l = [i for i in strings if i in file]
>>> if len(l) >= num:
print('found')
found
如果你喜欢单行本,这是我的建议:
# 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
如果您想检查常见项目(哪些并不重要),您可以使用 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')
strings = ("name", "last", "middle")
file = ["name","blabla","middle"]
for line in file:
if any(s in line for s in strings):
print ("found")
我想比较两个列表并检查公共字符串,当且仅当两个或多个 字符串相同时。 上面的代码适用于 one 但我希望它检查 two 关键字。
例如:它应该 只有 print(found)
如果 并且只有 'name' 和 'middle'被发现。不仅是 'name' 被发现。它应该检查 两个 个字符串。
首先,您可以使用 list comprehension
查找匹配项数量,然后使用 len > 2
或不使用
>>> num = 2
>>> l = [i for i in strings if i in file]
>>> if len(l) >= num:
print('found')
found
如果你喜欢单行本,这是我的建议:
# 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
如果您想检查常见项目(哪些并不重要),您可以使用 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')