Summing lists in python - is there a better way?

Is there a smarter way to do this? I want to create a new list by summing the indices of many other lists. I am new to programming and it seems like a very awkward method!

list1 = [1,2,3,4,5]
list2 = [1,1,1,4,1]
list3 = [1,22,3,1,5]
list4 = [1,2,5,4,5]
...
list100 = [4,5,6,7,8]

i = 0
while i < len(list1):
    mynewlist[i] = list1[i]+list2[i]+list3[i]+list4[i]+...list100[i]
    i = i+1
+5
source share
4 answers

This is a pretty good use case zip.

>>> list1 = [1,2,3,4,5]
>>> list2 = [1,1,1,4,1]
>>> list3 = [1,22,3,1,5]
>>> list4 = [1,2,5,4,5]
>>> [sum(x) for x in zip(list1, list2, list3, list4)]
[4, 27, 12, 13, 16]

or if you have data as a list of lists instead of separate lists:

>>> data = [[1,2,3,4,5], [1,1,1,4,1], [1,22,3,1,5], [1,2,5,4,5]]
>>> [sum(x) for x in zip(*data)]
[4, 27, 12, 13, 16]

Similarly, if you save your data as dictlists, you can use dict.itervalues()or dict.values()to get the values ​​of the list and use them in the same way:

>>> data = {"a":[1,2,3], "b":[3,4,4]}
>>> [sum(x) for x in zip(*data.itervalues())]
[4, 6, 7]

Please note that if your lists are of unequal length, it zipwill work until the shortest list length. For instance:

>>> data = [[1,2,3,4,5], [1,1], [1,22], [1,2,5]]
>>> [sum(x) for x in zip(*data)]
[4, 27]

, , itertools.izip_longest ( fillvalue). :

>>> data = [[1,2,3,4,5], [1,1], [1,22], [1,2,5]]
>>> [sum(x) for x in izip_longest(*data, fillvalue=0)]
[4, 27, 8, 4, 5]
+17

@Shawn , , , map , :

>>> list1 = [1,2,3,4,5]
>>> list2 = [1,1,1,4,1]
>>> list3 = [1,22,3,1,5]
>>> list4 = [1,2,5,4,5]
>>> map(sum, zip(list1, list2, list3, list4))
[4, 27, 12, 13, 16]
+6

: 100 .

list1 = [1,2,3,4,5]
list2 = [1,1,1,4,1]
list3 = [1,22,3,1,5]
list4 = [1,2,5,4,5]
...
list100 = [4,5,6,7,8]

-

list_of_lists = []
list_of_lists.append([1,2,3,4,5])
list_of_lists.append([1,1,1,4,1])
list_of_lists.append([1,22,3,1,5])
list_of_lists.append([1,2,5,4,5])
...

:

[sum(x) for x in zip(*list_of_lists)]
+1

python.

  • sum(list1) .
  • for
  • zip:

    list1 = [1,2,3,4,5]
    list2 = [1,1,1,4,1]
    list3 = [1,22,3,1,5]
    zip(list1,list2,list3)
    # matches up element n of each list with element n of the other lists
    #=> [(1, 1, 1), (2, 1, 22), (3, 1, 3), (4, 4, 1), (5, 1, 5)]
    # now you want to add up each of those tuples:
    [sum(t) for t in zip(list1,list2,list3)]
    #=> [3, 25, 7, 9, 11]
    

, , zip, itertools *args.

0

All Articles