How to find list intersection?

前端 未结 12 2271
别那么骄傲
别那么骄傲 2020-11-22 05:21
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 ac

12条回答
  •  醉话见心
    2020-11-22 05:41

    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))
    

提交回复
热议问题