2017-02-22 37 views
1

我有兩個列表,列表中有相同的len在Python中(對於這個例子來說是3)。從列表的2個列表中明智地提取公共元素

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. 

注意列表清單的每一行中的元素可以以任意順序出現。

回答

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

是'map(set,B)'由於'if b in'lookup? –

+0

@ Ev.Kounis,是的。 – falsetru

+0

然後+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'}] 

通知這最後的格式一個不是你指定的那個,但是它使用set相交爲這些類型的操作構建的離子。

+0

我喜歡使用集合+1,但也許'[set(x).intersection(y)for zip,(A,B)]'更整齊 –

+0

@Chris_Rands更多*整潔*如在?.. xD –

+0

那麼它保存第二個明確的'集合'調用和文檔談論非運營商形式爲「更具可讀性」,但你的方式也很好https://docs.python.org /3/library/stdtypes.html#set.intersection –

相關問題