How to find list intersection?

2019-01-01 08:52发布

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?

8条回答
高级女魔头
2楼-- · 2019-01-01 09:10

a = [1,2,3,4,5] b = [1,3,5,6] c = list(set(a).intersection(set(b)))

Should work like a dream. And, if you can, use sets instead of lists to avoid all this type changing!

查看更多
与君花间醉酒
3楼-- · 2019-01-01 09:10

A functional way can be achieved using filter and lambda operator.

list1 = [1,2,3,4,5,6]

list2 = [2,4,6,9,10]

>>> filter(lambda x:x in list1, list2)

[2, 4, 6]

Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:

>>> filter(lambda x:x not in list1, list2)
[9,10]
查看更多
忆尘夕之涩
4楼-- · 2019-01-01 09:12

Make a set out of the larger one:

_auxset = set(a)

Then,

c = [x for x in b if x in _auxset]

will do what you want (preserving b's ordering, not a's -- can't necessarily preserve both) and do it fast. (Using if x in a as the condition in the list comprehension would also work, and avoid the need to build _auxset, but unfortunately for lists of substantial length it would be a lot slower).

If you want the result to be sorted, rather than preserve either list's ordering, an even neater way might be:

c = sorted(set(a).intersection(b))
查看更多
美炸的是我
5楼-- · 2019-01-01 09:14

If, by Boolean AND, you mean items that appear in both lists, e.g. intersection, then you should look at Python's set and frozenset types.

查看更多
琉璃瓶的回忆
6楼-- · 2019-01-01 09:26

Using list comprehensions is a pretty obvious one for me. Not sure about performance, but at least things stay lists.

[x for x in a if x in b]

Or "all the x values that are in A, if the X value is in B".

查看更多
听够珍惜
7楼-- · 2019-01-01 09:27

If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using intersection():

a = [1,2,3,4,5]
b = [1,3,5,6]
set(a).intersection(b)
查看更多
登录 后发表回答