Python 获取两个列表的交集:简单易懂的示例
您可以使用 Python 中的 set() 函数来获取两个列表之间的交集。具体步骤如下:
- 将两个列表转换为
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/onss 著作权归作者所有。请勿转载和采集!