Document

python中怎么取两个列表 集合的交集

在python 3.x 版本中 set 中有函数intersection()

intersection() 方法用于返回两个或更多集合中都包含的元素,即交集。

语法:

    set.intersection(set1, set2 ... etc)

参数:

  • set1 -- 必需,要查找相同元素的集合
  • set2 -- 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开

 

返回值:

   返回一个新的集合

 

实操:

a = [5, 6, 7, 8, 9]
b = [4, 6, 7, 8, 10]
print(set(a).intersection(set(b)))


a = {5, 6, 7, 8, 9}
b = {4, 6, 7, 8, 10}
print(a.intersection(b))


输出结果:

    {8, 6, 7}
    {8, 6, 7}

 

 

 

 

 



posted @ 2020-08-27 14:20  苏什么苏  阅读(3963)  评论(0编辑  收藏  举报