0

list_a文字列(および)を含む2つのネストされたリストがありますlist_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_blist_a数え、list_aを次のように新しいリストとして1つの追加の列(出現回数)とマージしたいと思います。

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.6dict((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 に答える