简体   繁体   中英

python matching list items

I'm using python 2.6 current output

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. and not outputting it twice.

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

Using 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM