簡體   English   中英

python匹配列表項

[英]python matching list items

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

使用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)]
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
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM