如何找到列表交集? [英] How to find list intersection?

查看:131
本文介绍了如何找到列表交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c

实际输出:[1,3,5,6] 预期输出:[1,3,5]

actual output: [1,3,5,6] expected output: [1,3,5]

如何在两个列表上实现布尔AND操作(列表交集)?

How can we achieve a boolean AND operation (list intersection) on two lists?

推荐答案

如果顺序并不重要,并且您不必担心重复,那么可以使用集合交集:

If order is not important and you don't need to worry about duplicates then you can use set intersection:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

这篇关于如何找到列表交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆