Algorithm in Python To Solve This Problem
I have a list of lists such as: [[foo,1],[baz,1],[foo,0],[bar,3],[foo,1],[bar,2],[baz,2]]
.
I 开发者_如何学Pythonwant to get all the different items in the inner lists and find the total number of them.
I mean the result should be like: [[foo,2],[bar,5],[baz,3]]
. How can I do this task?
Thanks in advance.
Create a dictionary
D = {}
for item in list:
left,right=item
D[left] = D.get(left, 0) + right
There may be faster ways to do this though.
As suggested in the comments by Joce, Gnibbler and Blair you coud do this to get a list again.
# To get a list of lists
pairs = map(list, D.items())
# To get a list of tuples
pairs = D.items()
The defaultdict makes this fairly easy:
import collections
items = [['foo',1],['baz',1],['foo',0],['bar',3],['foo',1],['bar',2],['baz',2]]
totals = collections.defaultdict(int)
for key, value in items:
totals[key] += value
print totals
When run, this gives
defaultdict(<type 'int'>, {'bar': 5, 'foo': 2, 'baz': 3})
If you want a list output, just pull the items from the dictionary
print totals.items()
and you get
[('bar', 5), ('foo', 2), ('baz', 3)]
If you really want a list-of-lists at the end,
print [list(item) for item in totals.items()]
which gives you
[['bar', 5], ['foo', 2], ['baz', 3]]
You can use itertools.groupby.
>>> import operator
>>> import itertools
>>> data = [['foo',1],['baz',1],['foo',0],['bar',3],['foo',1],['bar',2],['baz',2
]]
>>> {i:sum(k[1] for k in j)
... for i, j in itertools.groupby(sorted(data, key=operator.itemgetter(0)),
... key=operator.itemgetter(0))}
{'baz': 3, 'foo': 2, 'bar': 5}
If you are using Python 3.2 (and 2.7) then you can do:
>>> from collections import Counter
>>> items = [['foo',1],['baz',1],['foo',0],['bar',3],['foo',1],['bar',2],['baz',2]]
>>> Counter(sum(( [key]*count for key,count in items), []))
Counter({'bar': 5, 'baz': 3, 'foo': 2})
>>> Counter(sum(( [key]*count for key,count in items), [])).most_common()
[('bar', 5), ('baz', 3), ('foo', 2)]
>>>
精彩评论