可以使用Python的set集合和交集运算符来比较多个列表。代码示例如下:
list1 = [1, 2, 3, 4] list2 = [2, 4, 6, 8] list3 = [3, 5, 7, 9]
result = set(list1) & set(list2) & set(list3)
print(result)
输出结果为:{ }
如果要获取共同元素,我们需要使用“&”运算符、intersection()函数或者intersection_update()方法。例如:
list1 = [1, 2, 3, 4] list2 = [2, 4, 6, 8] list3 = [3, 5, 7, 9]
set1 = set(list1) set2 = set(list2) set3 = set(list3)
result = set1 & set2 & set3
result = set1.intersection(set2).intersection(set3)
set1.intersection_update(set2) result = set1.intersection(set3)
print(result)
输出结果为:{ }
下一篇:比较多个列表的某些索引值