简体   繁体   中英

Sum of elements of a 2d list in Python

I have a 2D list

a = [[1,2], [3,4]...]

I want to do something like this: 1+3 and 2+4 and store result in another array

b = [4, 6]

Like 0th element of array at index 0 which is 1, added with 0th element of array at index 1 which is 3, and 2 added with 4, and so on.

How can I do this, without looping or generators as looping over a large list is comparatively slower than sum and zip functions.

Using just sum and zip as you mention, however zip still returns a generator, which is memory efficient, not sure why you think otherwise.

list(map(sum, (zip(*a))))

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