gpt4 book ai didi

python - 检查三个列表中的公共(public)元素 : it checks for identical lists instead

转载 作者:太空狗 更新时间:2023-10-30 01:05:12 25 4
gpt4 key购买 nike

我需要输入三个列表并进行 bool 检查是否所有列表都有共同的元素。到目前为止,代码的主要部分如下所示:

def in_all_three(listA, listB, listC):
for x in listA:
if x in listB and x in listC:
return True
else:
return False

我不知道为什么,但它只在列表相同时返回 True。我的代码有什么问题?

最佳答案

您可以使用 sets 的交集以此目的。

def check_common_element(listA, listB, listC):
common_elements = set.intersection(set(listA), set(listB), set(listC))
if common_elements:
return True
else:
return False

# Test case 1: Testing when there is a common value among lists
list_a = [1,2,3]
list_b = [1,5,6]
list_c = [1,8,9]

print(check_common_element(list_a,list_b,list_c))
# output: True

# Test case 2: Testing when there is no common value among lists
list_a = [1,2,3]
list_b = [1,5,6]
list_c = [7,8,9]

print(check_common_element(list_a,list_b,list_c))
# output: False

正如@Reti43 所建议的,您可以执行 return bool(common_elements) 而不是 if-else 作为更好的选择,原因在下面的评论中有所描述。在这种情况下,修改后的函数将如下所示:

def check_common_element(listA, listB, listC):
common_elements = set.intersection(set(listA), set(listB), set(listC))
return bool(common_elements)

关于python - 检查三个列表中的公共(public)元素 : it checks for identical lists instead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46890714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com