python匹配列表项

时间:2013-05-31 01:17:17

标签: python string parsing dictionary

我正在使用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

3 个答案:

答案 0 :(得分: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)]

答案 1 :(得分: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

答案 2 :(得分: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)]