簡體   English   中英

如何檢查一個列表是否包含另一個列表的 2 個元素?

[英]How do I check if one list contains 2 elements of another list?

我希望能夠檢查一個列表是否包含另一個列表的 2 個元素(總共有 3 個元素)

例如:

list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]

if #list2 contains any 2 elements of list1:
    print("yes, list 2 contains 2 elements of list 1")
else:
    print("no, list 2 does not contain 2 elements of list 1")

我將使用以下問題中描述的類似描述,只是這次檢查集合交集的長度: 如何找到列表交集?

list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]

if len(list(set(a) & set(b))) == 2:
    print("yes, list 2 contains 2 elements of list 1")
else:
    print("no, list 2 does not contain 2 elements of list 1")

您可以編寫一個 function 來檢查兩個列表之間的共同元素,然后驗證該元素的數量是否等於 2。

例如:

def intersection(list1, list2): 
     lst3 = [value for value in list1 if value in list2] 
     return lst3 


list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]

if len(intersection(list1, list2) == 2):
    print("yes, list 2 contains 2 elements of list 1")
else:
    print("no, list 2 does not contain 2 elements of list 1")

def my_func(list1, list2):
    count = 0
    for i in list1:
        for j in list2:
            if(i == j) : count += 1
    print(count)
    if(count >= 2) : return True
    else: return False


list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]

if my_func(list1, list2):#list2 contains any 2 elements of list1:
    print("yes, list 2 contains 2 elements of list 1")
else:
    print("no, list 2 does not contain 2 elements of list 1")

您可以使用itertools.combinations()list2獲取所有兩個元素的集合,並查看它們是否是list1的子集:

import itertools

if any(set(comb).issubset(set(list1)) for comb in itertools.combinations(list2, 2)):
    print("yes, ...")
...
count = 0
for ele in list2:
    if ele in list1:
        count += 1
if count == 2:
    print ("yes, list 2 contains 2 elements of list 1")
else:
    print ("no, list 2 does not contain 2 elements of list 1")
list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]

if len(set(list1).intersection(set(list2))) == 2:
    print("yes, list 2 contains 2 elements of list 1")
else:
    print("no, list 2 does not contain 2 elements of list 1")

.intersection 方法接受兩個集合並找出它們之間的共同點。 如果它們之間的共同點是 2 個元素,那么你就有了你想要的。

這有效:

list1 = ["a", "b", "c"]
list2 = ["a", "f", "g", "b"]
val = 0
for idx in list1:
    for idx2 in list2:
        if idx == idx2:
            val += 1
if val == 2:
    print("yes, list 2 contains 2 elements of list 1")
else:
    print("no, list 2 does not contain 2 elements of list 1")

暫無
暫無

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

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