可以使用set函数将两个列表转换为集合,然后使用集合的交集、差集等操作进行比较。也可以使用循环遍历列表进行比较。
示例代码:
list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] set1 = set(list1) set2 = set(list2)
intersection = set1.intersection(set2) print("两个列表的交集:", intersection)
difference1 = set1.difference(set2) difference2 = set2.difference(set1) print("第一个列表独有的元素:", difference1) print("第二个列表独有的元素:", difference2)
union = set1.union(set2) print("两个列表的并集:", union)
list1 = [1, 2, 3, 4, 5] list2 = [3, 4, 5, 6, 7] common = [] for i in list1: if i in list2: common.append(i) print("两个列表的共同元素:", common)