0

我正在使用 python 2.6 电流输出

mylist = [('log:A', '1009.2'), ('log:B', '938.1'), ('log:C', '925.7'), ('log:C', '925.7')]

我正在尝试添加值以产生以下结果:从最高到最低排名。我遇到的问题是将所有内容与 log:C 标签一起添加。并且不输出两次。

log:C = 1851.4
log:A = 1009.2
log:B = 938.1
4

3 回答 3

3

使用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

要根据值获取排序的项目列表:

>>> sorted(dic.items(), key = lambda x: x[1], reverse = True)
[('log:C', 74), ('log:B', 54), ('log:D', 24), ('log:A', 22)]

更新:根据您的新输入

>>> 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)]
于 2013-05-31T01:24:02.660 回答
2
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   

印刷:

{'log:D': [24], 'log:A': [22], 'log:C': [74], 'log:B': [44, 10]}

然后将它们相加:

for k in sorted(res):
   print k, sum(res[k])

印刷:

log:A 22
log:B 54
log:C 74
log:D 24
于 2013-05-31T01:24:27.570 回答
0
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)]
于 2013-05-31T01:28:52.777 回答