获取两个List之间的交集
您可以使用Python中的set()函数来获取两个List之间的交集。具体步骤如下:
- 将两个List转换为set类型。
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
set1 = set(list1)
set2 = set(list2)
- 使用&运算符获取两个set之间的交集。
intersection = set1 & set2
- 将交集转换为List类型。
result = list(intersection)
完整代码如下:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
set1 = set(list1)
set2 = set(list2)
intersection = set1 & set2
result = list(intersection)
print(result)
结果为:[3, 4]
原文地址: https://www.cveoy.top/t/topic/fHO3 著作权归作者所有。请勿转载和采集!