[英]python matching list items
I'm using python 2.6 current output 我正在使用python 2.6当前输出
mylist = [('log:A', '1009.2'), ('log:B', '938.1'), ('log:C', '925.7'), ('log:C', '925.7')]
I'am trying to add the values to produce the follow: Ranked highest to lowest. 我正在尝试将这些值相加以产生以下结果:排名从高到低。 The problem I'am having is adding everthing with a log:C tag together.
我遇到的问题是将所有内容与log:C标签一起添加。 and not outputting it twice.
而不输出两次。
log:C = 1851.4
log:A = 1009.2
log:B = 938.1
Using collections.defaultdict
: 使用
collections.defaultdict
:
>>> strs = "log:A 22 log:B 44 log:C 74 log:D 24 log:B 10"
>>> from collections import defaultdict
>>> dic = defaultdict(int)
>>> it = iter(strs.split())
>>> for k in it:
... dic[k] += int(next(it))
...
>>> for k,v in sorted(dic.items(), key = lambda x: x[1], reverse = True):
... print k,v
...
log:C 74
log:B 54
log:D 24
log:A 22
To get a sorted list of items based on values: 要获得基于值的项目排序列表:
>>> sorted(dic.items(), key = lambda x: x[1], reverse = True)
[('log:C', 74), ('log:B', 54), ('log:D', 24), ('log:A', 22)]
Update: Based on your new input 更新:根据您的新输入
>>> mylist = [('log:A', '1009.2'), ('log:B', '938.1'), ('log:C', '925.7'), ('log:C', '925.7')]
>>> dic = defaultdict(int)
>>> for k,v in mylist:
dic[k] += float(v)
...
>>> sorted(dic.items(), key = lambda x: x[1], reverse = True)
[('log:C', 1851.4), ('log:A', 1009.2), ('log:B', 938.1)]
mystr = 'log:A 22 log:B 44 log:C 74 log:D 24 log:B 10'
li=mystr.split()
res={}
for k,v in zip(li[::2],li[1::2]):
res.setdefault(k,[]).append(int(v))
print res
Prints: 打印:
{'log:D': [24], 'log:A': [22], 'log:C': [74], 'log:B': [44, 10]}
Then just sum them: 然后总结一下:
for k in sorted(res):
print k, sum(res[k])
Prints: 打印:
log:A 22
log:B 54
log:C 74
log:D 24
import collections
import operator
mystr = "log:A 22 log:B 44 log:C 74 log:D 24 log:B 10"
s = mystr.split()
d = collections.defaultdict(int)
for i in xrange(0, len(s), 2):
d[s[i]] += int(s[i+1])
# alternate way:
# i = iter(s)
# for k, v in itertools.izip(i, i):
# d[k] += int(v)
result = sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True)
# [('log:C', 74), ('log:B', 54), ('log:D', 24), ('log:A', 22)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.