繁体   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