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

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

问题描述

a = [1,2,3,4,5]b = [1,3,5,6]c = a 和 b打印 c

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

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

解决方案

如果顺序不重要,而且你不需要担心重复,那么你可以使用集合交集:

<预><代码>>>>a = [1,2,3,4,5]>>>b = [1,3,5,6]>>>列表(集合(a)和集合(b))[1, 3, 5]

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

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

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天全站免登陆