2012-09-25 96 views
0

我有兩個嵌套列表與字符串(list_alist_b),詳細信息如下:比較Python的嵌套列表和計數複製

list_a = [ 
('shop1', 'stand1', 'shelf1', 'fruit1'), 
('shop1', 'stand1', 'shelf2', 'fruit2'), 
('shop1', 'stand1', 'shelf3', 'fruit3'), 
('shop1', 'stand2', 'shelf1', 'fruit1'), 
('shop1', 'stand2', 'shelf2', 'fruit2'), 
('shop1', 'stand2', 'shelf3', 'fruit3'), 
('shop2', 'stand3', 'shelf1', 'fruit1'), 
('shop2', 'stand3', 'shelf2', 'fruit2'), 
('shop2', 'stand3', 'shelf3', 'fruit3') 
] 
list_b = [ 
('shop1', 'stand1', 'shelf1', 'fruit1'), 
('shop1', 'stand1', 'shelf2', 'fruit2'), 
('shop1', 'stand1', 'shelf2', 'fruit2'), 
('shop1', 'stand1', 'shelf3', 'fruit3'), 
('shop1', 'stand1', 'shelf3', 'fruit3'), 
('shop1', 'stand1', 'shelf3', 'fruit3'), 
('shop1', 'stand2', 'shelf1', 'fruit1'), 
('shop1', 'stand2', 'shelf1', 'fruit1'), 
('shop1', 'stand2', 'shelf1', 'fruit1'), 
('shop1', 'stand2', 'shelf2', 'fruit2'), 
('shop1', 'stand2', 'shelf2', 'fruit2'), 
('shop1', 'stand2', 'shelf2', 'fruit2'), 
('shop1', 'stand2', 'shelf3', 'fruit3'), 
('shop2', 'stand3', 'shelf1', 'fruit1'), 
('shop2', 'stand3', 'shelf1', 'fruit1'), 
('shop2', 'stand3', 'shelf2', 'fruit2'), 
('shop2', 'stand3', 'shelf3', 'fruit3'), 
('shop2', 'stand3', 'shelf3', 'fruit3'), 
('shop2', 'stand3', 'shelf3', 'fruit3') 
] 

,我想找到list_b相同的行中list_a,算上「複製」行和合並使用一個額外的列(發生次數)list_a作爲一個新的列表,這樣下面:

result_list = [ 
('shop1', 'stand1', 'shelf1', 'fruit1', 1), 
('shop1', 'stand1', 'shelf2', 'fruit2', 2), 
('shop1', 'stand1', 'shelf3', 'fruit3', 3), 
('shop1', 'stand2', 'shelf1', 'fruit1', 3), 
('shop1', 'stand2', 'shelf2', 'fruit2', 3), 
('shop1', 'stand2', 'shelf3', 'fruit3', 1), 
('shop2', 'stand3', 'shelf1', 'fruit1', 2), 
('shop2', 'stand3', 'shelf2', 'fruit2', 1), 
('shop2', 'stand3', 'shelf3', 'fruit3', 3) 
] 

有什麼快速有效的方式做到這一點?

+2

聽起來就像你想要一個數據庫。 – phg

+0

可能的重複 - http://stackoverflow.com/questions/642763/python-intersection-of-two-lists或http://stackoverflow.com/questions/2029795/comparing-python-nested-lists –

+0

WEll,didn沒有注意到你想要的頻率也..然後這些鏈接不包含你想要的.. –

回答

1
dict_a = {row: 0 for row in list_a} 
for row in list_b: 
    if row in dict_a: 
     dict_a[row] += 1 

result = [row + (dict_a[row],) for row in list_a] 

在Python 2.6中使用dict((row, 0) for row in list_a)而不是字典解析。

+0

工程很漂亮,但我忘了提及我的Python版本,它是2.6,所以我改變了一下。非常感謝你! – jusef

1

使用Counter()

>>> from collections import Counter 
    >>> count=Counter(list_b) 
    >>> [list(x)+[count[x]] for x in list_a] 

    [['shop1', 'stand1', 'shelf1', 'fruit1', 1], 
    ['shop1', 'stand1', 'shelf2', 'fruit2', 2], 
    ['shop1', 'stand1', 'shelf3', 'fruit3', 3], 
    ['shop1', 'stand2', 'shelf1', 'fruit1', 3], 
    ['shop1', 'stand2', 'shelf2', 'fruit2', 3], 
    ['shop1', 'stand2', 'shelf3', 'fruit3', 1], 
    ['shop2', 'stand3', 'shelf1', 'fruit1', 2], 
    ['shop2', 'stand3', 'shelf2', 'fruit2', 1], 
    ['shop2', 'stand3', 'shelf3', 'fruit3', 3]]` 
+0

工程很漂亮,但我忘了提及我的Python版本,它的2.6,所以我已經改變了一點。非常感謝你! – jusef

+0

你可以在pythom 2.6中使用'defaultdict'。 –