3
score=[
 ['5.00', '4.30', '2.50', '3.60', '1.30', '5.00'],
 ['80.00', '8.00', '32.00', '13.60', '20.00', '80.00'], 
 ['12.00', '6.00', '7.20', '8.40', '9.60', '12.00'],
 ['3.00', '1.20', '2.04', '1.08', '0.84', '3.00']
]

I want

a = 5 + 80 + 12 + 3   # add first element of all lists in score
b = 4.3 + 8 + 6 + 1.2   # add second element of all lists in score
c = 2.5 + 32 + 7.2 + 2.04  # etc ...
d = 3.6 + 13.6 + 8.4 + 1.08  # ...
e = 1.3 + 20 + 9.6 + 0.84
f = 5 + 80 + 12 + 3

But I don't know how many lists are in score, so I can't use zip(). How do I sum all elements having the same index in different lists in python?

user
  • 5,370
  • 8
  • 47
  • 75
  • Possible duplicate of [Add SUM of values of two LISTS into new LIST](http://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list) – Valentin Lorentz Dec 03 '15 at 19:51

3 Answers3

2

Actually, you can use zip:

>>> map(sum, map(lambda l: map(float, l), zip(*score)))
[100.0, 19.5, 43.74, 26.68, 31.74, 100.0]
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
1

The best way to do this is using the zip built-in class1 or function2 and the *-operator to unpack the "scores" into variables using the a simple assignment operation. You then use the sum built-in function to calculate the sum. Of course you will need to convert you element to float using float and map

>>> score = [
... ['5.00', '4.30', '2.50', '3.60', '1.30', '5.00'],
...  ['80.00', '8.00', '32.00', '13.60', '20.00', '80.00'], 
... ['12.00', '6.00', '7.20', '8.40', '9.60', '12.00'],
...  ['3.00', '1.20', '2.04', '1.08', '0.84', '3.00']
... ]
>>> a, b, c, d, e, f = [sum(map(float, i)) for i in zip(*score)]
>>> a
100.0
>>> b
19.5
>>> c
43.74
>>> d
26.68
>>> e
31.74
>>> f
100.0

  1. Python 3.x
  2. Python 2.x
styvane
  • 59,869
  • 19
  • 150
  • 156
0

Slightly different way:

score = [
    ['5.00', '4.30', '2.50', '3.60', '1.30', '5.00'],
    ['80.00', '8.00', '32.00', '13.60', '20.00', '80.00'], 
    ['12.00', '6.00', '7.20', '8.40', '9.60', '12.00'],
    ['3.00', '1.20', '2.04', '1.08', '0.84', '3.00']
]

def sum_same_elements(l):
    l_float = [map(float, lst) for lst in l]
    to_sum  = []
    for i in range(len(l[0])):
        lst_at_index = []
        for lst in l_float:
            lst_at_index.append(lst[i])
        to_sum.append(lst_at_index)
    return map(sum, to_sum)

print sum_same_elements(score)
Andrew Winterbotham
  • 1,000
  • 7
  • 13