Skip to main content
 首页 » 编程设计

python之从列表的 2 个列表中按行提取公共(public)元素

2025年05月04日22xing901022

我在 Python 中有两个具有相同 len 的列表列表(在这个例子中假设为 3)。

A = [['Horse','Duck','Goat'],['Rome','New York'],['Apple','Rome','Goat','Boat']] 
 
B = [['Carrot','Duck'],['Car','Boat','Plane'],['Goat','Apple','Boat']] 

我想匹配每一行中的元素并创建一个新的公共(public)元素列表。我需要的结果输出是:

c = [['Duck'],[],['Apple','Goat','Boat']] 

和,

d = [1,0,3] ; where d is a list with the count of common elements at each row. 

请注意,在列表列表的每一行中,元素可以以任何顺序出现。

请您参考如下方法:

使用 list comprehension和 zip :

>>> A = [['Horse','Duck','Goat'],['Rome','New York'], 
         ['Apple','Rome','Goat','Boat']] 
>>> B = [['Carrot','Duck'],['Car','Boat','Plane'], 
         ['Goat','Apple','Boat']] 
>>> c = [[x for x in a if x in b] for a, b in zip(A, map(set, B))] 
>>> d = [len(x) for x in c] 
>>> # or d = list(map(len, c))    # you can omit `list` in python 2.x 
>>> c 
[['Duck'], [], ['Apple', 'Goat', 'Boat']] 
>>> d 
[1, 0, 3]