Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum lists with different lengths

What's the best way to sum two or more lists even if they have different lengths?

For example I have:

lists = [[1, 2], [0, 3, 4], [5]]

and the result should be:

result = [6, 5, 4]
like image 265
enrico.bacis Avatar asked Oct 22 '12 12:10

enrico.bacis


People also ask

How do you add two unequal lists in Python?

Example: Use + Operator to Add Elements of Two Lists Numpy arrays are given as input and the addition of elements is done using + operator. In order to print the result as Python List, use to_list() function.

Can you sum lists in Python?

Python's built-in function sum() is an efficient and Pythonic way to sum a list of numeric values. Adding several numbers together is a common intermediate step in many computations, so sum() is a pretty handy tool for a Python programmer.

How do you sum a list of integers?

The second method for calculating the sum of a list of integers is by using the collect() terminal operation: List<Integer> integers = Arrays. asList(1, 2, 3, 4, 5); Integer sum = integers. stream() .


2 Answers

You can use itertools.izip_longest(), and use a fillvalue equal to 0

In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
Out[6]: [6, 5, 4]

for Python < 2.6:

In [27]: ml = max(map(len, lists))

In [28]: ml       #length of the longest list in lists
Out[28]: 3

In [29]: [sum(x) for x in zip(*map(lambda x:x+[0]*ml if len(x)<ml else x, lists))]
Out[29]: [6, 5, 4]
like image 140
Ashwini Chaudhary Avatar answered Sep 20 '22 18:09

Ashwini Chaudhary


#You can do the same without using predefined header files.
def sumlists(a,b,c):
    sumlist = []
    while(len(a)!=len(b) or len(a)!=len(c)):
        if len(a)>len(b):
            b.append(0)
        if len(a)>len(c):
            c.append(0)
        elif len(b)>len(a):
            a.append(0)
        if len(b)>len(c):
             c.append(0)
        elif len(c)>len(a):
            a.append(0)
        if len(c)>len(b):
             b.append(0)
    for i,j,k in zip(a,b,c):
         sumlist.append(i+j+k)
    return sumlist
 print(sumlists([1,2],[0,3,4],[5]))
like image 25
N S Avatar answered Sep 22 '22 18:09

N S