Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

python - finding duplicates in a list of lists

I am using Python 2.7 and am trying to de-duplicate a list of lists and merge the values of the duplicates.

Right now I have:

original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]]

I want to match on the first element of each nested list and then add the values of the second element. I want to end up with this (the order of the final list does not matter):

ideal_output = [['a', 2], ['b', 7], ['c', 2]]

So far I have some code that will find me the duplicate values based on the first element of each nested list:

for item in original_list:
    matches = -1
    for x in original_list:
        if (item[0] == x[0]):
            matches += 1
    if matches >= 1: 
        if item[0] not in duplicates_list:
            duplicates_list.append(item[0])

From here I need to search for all duplicates_list items that are in original_list and add up the values, but I am not sure what the best way to do that is.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lots of good answers, but they all use rather more code than I would for this, so here's my take, for what it's worth:

totals = {}
for k,v in original_list:
  totals[k] = totals.get(k,0) + v

# totals = {'a': 2, 'c': 2, 'b': 7}

Once you have a dict like that, from any of these answers, you can use items to get a list of tuples:

totals.items()
# => [('a', 2), ('c', 2), ('b', 7)]

And map list across the tuples to get a list of lists:

map(list, totals.items())
# => [['a', 2], ['c', 2], ['b', 7]]

And sort if you want them in order:

sorted(map(list, totals.items()))
# => [['a', 2], ['b', 7], ['c', 2]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...