0

我有两个带有字符串(list_alist_b)的嵌套列表,详细信息如下:

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_bin 中找到相同的行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)
]

有没有快速有效的方法来做到这一点?

4

3 回答 3

2
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)而不是字典理解。

于 2012-09-25T18:03:26.387 回答
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]]`
于 2012-09-25T18:02:30.507 回答
0

这些不是嵌套列表而是元组。这实际上是你的储蓄。请参阅 计算 Python 列表中值频率的最有效方法? 这应该几乎可以立即工作。要获得重复项,请取出keys()两个字典,并计算它们的差异。

于 2012-09-25T17:59:48.440 回答