从2个列表中逐行提取常用元素

时间:2017-02-22 15:12:42

标签: python list

我有两个列表,在Python中使用相等的len(在本例中假设为3)。

A = [['Horse','Duck','Goat'],['Rome','New York'],['Apple','Rome','Goat','Boat']]

B = [['Carrot','Duck'],['Car','Boat','Plane'],['Goat','Apple','Boat']]

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

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

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

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

2 个答案:

答案 0 :(得分:3)

使用list comprehensionzip

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

答案 1 :(得分:2)

另一种清单理解:

c = [[x for x in y if x in B[i]] for i, y in enumerate(A)]
# [['Duck'], [], ['Apple', 'Goat', 'Boat']]

d = [len(x) for x in c]
# [1, 0, 3]

或者,你也可以使用它:

res = [set(x) & set(y) for x, y in zip(A, B)]
# or  [set(x).intersection(y) for x, y in zip(A, B)] as @Chris_Rands suggested
# [{'Duck'}, set(), {'Apple', 'Goat', 'Boat'}]

请注意,最后一个格式的格式不是您指定的格式,但它使用为这些类型的操作构建的集合交集。