简体   繁体   中英

How to add column elements of a 2D list and return result in a list?

Write a function that takes a two-dimensional list (list of lists) of numbers as argument and returns a list which includes the sum of each column. Assume that the number of columns in each row is the same.

I know how to traverse a row in a multidimensional list but have been facing problem on how to traverse the column elements of a multidimensional list. I'm just a beginner with python. There's no logic I can come up with using for loop or any of the list manipulation methods. I haven't come across the advance topics of lambda or anything of that sort. Any help would be appreciated.

Transpose and sum each column:

In [1]: arr = [[1,2,3],
         [4,5,6]]

In [2]: list(map(sum, zip(*arr)))
Out[2]: [5, 7, 9]

zip(*arr) gives you the columns:

In [3]: list(zip(*arr))
Out[3]: [(1, 4), (2, 5), (3, 6)]

Then mapping sum on each column gives you the sum for each.

If you prefer a list comp:

In [5]: [sum(col) for col in zip(*arr)]
Out[5]: [5, 7, 9]

That's not the most beautiful piece of code I've ever come up with, but it should do the trick. If you would use packages such as numpy , things get significantly easier.

a = [1,2,3]
b = [4,5,6]
res = []
for i in range(len(a)):
   res.append(a[i] + b[i])

A 2 dimensional list can be expressed a list of lists. That is

>>> mylist = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
>>>len(mylist)

You can now create a sum using nested for loops. Note that this assumes that there are the same number of elements in each column.

mysum = [0, 0, 0, 0]

for i in range(len(mylist)):
    for j in range(len(mylist[0])):
        mysum[i] += mylist[i][j]

print mysum

If you want to make it more general (and allow for different sized columns) without having to create an explicit mysum list you can use the following code.

mysum = []
for i in range(len(mylist)):
    total = 0
    for j in range(len(mylist[i])):
        total += mylist[i][j]
    mysum.append(total)

print mysum
def _sum_of_columns_sample_(sample_list):
cols = len(sample_list[0])
mylist = []
for c in range(cols):
    column_sum = 0
    for row in sample_list:
        column_sum += row[c]
    mylist.append(column_sum)
return mylist

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