簡體   English   中英

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

我想比較兩個列表,並檢查是否有共同的字符串, 並且僅當兩個或多個字符串相同時才可以。 上面的代碼適用於一個,但我希望它檢查兩個關鍵字。

例如:它應該 print(found) ,當且僅當 “名”和“中部”中找到。 不僅是找到“名稱”。 它應該檢查兩個字符串。

如果要檢查常見項目(可以選擇哪個不重要),則可以使用setintersection

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

首先,您可以使用list comprehension len > 2找到匹配數,然后選擇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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM