简体   繁体   中英

Summing up numbers in a defaultdict(list)

I've been experimenting trying to get this to work and I've exhausted every idea and web search. Nothing seems to do the trick. I need to sum numbers in a defaultdict(list) and i just need the final result but no matter what i do i can only get to the final result by iterating and returning all sums adding up to the final. What I've been trying generally,

d = { key : [1,2,3] }
running_total = 0

#Iterate values
for value in d.itervalues:
  #iterate through list inside value
  for x in value:       
    running_total += x
    print running_total

The result is : 1 , 3 , 6 I understand its doing this because its iterating through the for loop. What i dont get is how else can i get to each of these list values without using a loop? Or is there some sort of method iv'e overlooked?

To be clear i just want the final number returned eg 6

EDIT I neglected a huge factor , the items in the list are timedealta objects so i have to use .seconds to make them into integers for adding. The solutions below make sense and I've tried similar but trying to throw in the .seconds conversion in the sum statement throws an error.

d = { key : [timedelta_Obj1,timedelta_Obj2,timedelta_Obj3] }

我认为这将为您工作:

sum(td.seconds for sublist in d.itervalues() for td in sublist)

Try this approach:

from datetime import timedelta as TD

d = {'foo' : [TD(seconds=1), TD(seconds=2), TD(seconds=3)],
     'bar' : [TD(seconds=4), TD(seconds=5), TD(seconds=6), TD(seconds=7)],
     'baz' : [TD(seconds=8)]}

print sum(sum(td.seconds for td in values) for values in d.itervalues())

You could just sum each of the lists in the dictionary, then take one final sum of the returned list.

>>> d = {'foo' : [1,2,3], 'bar' : [4,5,6,7], 'foobar' : [10]}

# sum each value in the dictionary
>>> [sum(d[i]) for i in d]
[10, 6, 22]

# sum each of the sums in the list
>>> sum([sum(d[i]) for i in d])
38

If you don't want to iterate or to use comprehensions you can use this:

d = {'1': [1, 2, 3], '2': [3, 4, 5], '3': [5], '4': [6, 7]}

print(sum(map(sum, d.values())))

If you use Python 2 and your dict has a lot of keys it's better you use imap (from itertools ) and itervalues

from itertools import imap

print sum(imap(sum, d.itervalues())) 

Your question was how to get the value "without using a loop". Well, you can't. But there is one thing you can do: use the high performance itertools .

If you use chain you won't have an explicit loop in your code. chain manages that for you.

>>> data = {'a': [1, 2, 3], 'b': [10, 20], 'c': [100]}
>>> import itertools
>>> sum(itertools.chain.from_iterable(data.itervalues()))
136

If you have timedelta objects you can use the same recipe.

>>> data = {'a': [timedelta(minutes=1), 
                  timedelta(minutes=2), 
                  timedelta(minutes=3)], 
            'b': [timedelta(minutes=10), 
                  timedelta(minutes=20)], 
            'c': [timedelta(minutes=100)]}
>>> sum(td.seconds for td in itertools.chain.from_iterable(data.itervalues()))
8160

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