给定两个输入列表,如何创建两个输入共用的元素列表?

例如:对于输入[1,2,3,4,5,6]和[3,5,7,9],结果应该是[3,5];输入[‘这个’,‘这’,' n ', ', ']和[‘这个’,‘不’,‘,’,','],结果应该[‘这个’,‘,’]。


参见: 在Python中,如何从两个列表中找到常用词,同时保持词序?(维持秩序) Python -多个列表的交集?(用于计算>= 3个列表之间的交集) 两个包含重复项的列表的交集?(保持重复元素)


当前回答

集合是另一种解法

a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}

其他回答

使用Python的集合交集:

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]

使用集合交叉,set(list1) & set(list2)

>>> def common_elements(list1, list2):
...     return list(set(list1) & set(list2))
...
>>>
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>>
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
>>>
>>>

注意,结果列表可能与原始列表顺序不同。

你可以使用numpy来解决这个问题:

import numpy as np

list1 = [1, 2, 3, 4, 5, 6]
list2 = [3, 5, 7, 9]

common_elements = np.intersect1d(list1, list2)
print(common_elements)

Common_elements将是numpy数组:[3 5]。

集合是另一种解法

a = [3,2,4]
b = [2,3,5]
set(a)&set(b)
{2, 3}

使用发电机:

common = (x for x in list1 if x in list2)

这样做的好处是,即使在使用庞大的列表或其他庞大的可迭代对象时,它也会在常数时间内(几乎立即)返回生成器。

例如,

list1 =  list(range(0,10000000))
list2=list(range(1000,20000000))
common = (x for x in list1 if x in list2)

对于list1和list2的这些值,这里的所有其他答案都将花费很长时间。

然后,您可以用

for i in common: print(i)