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

例如:对于输入[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}

其他回答

集合是另一种解法

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

你可以使用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 = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))

使用Python的集合交集:

>>> list1 = [1,2,3,4,5,6]
>>> list2 = [3, 5, 7, 9]
>>> list(set(list1).intersection(list2))
[3, 5]
list1=[123,324523,5432,311,23]
list2=[2343254,34234,234,322123,123,234,23]
common=[]
def common_elements(list1,list2):
    for x in range(0,len(list1)):
        if list1[x] in list2:
            common.append(list1[x])
            
common_elements(list1,list2)
print(common)