您可以使用 Python 中的 set() 函数来获取两个列表之间的交集。具体步骤如下:

  1. 将两个列表转换为 set 类型。
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
set1 = set(list1)
set2 = set(list2)
  1. 使用 & 运算符获取两个 set 之间的交集。
intersection = set1 & set2
  1. 将交集转换为 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]

Python 获取两个列表的交集:简单易懂的示例

原文地址: https://www.cveoy.top/t/topic/onss 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录