sum of N lists element-wise python

后端 未结 2 1365
野性不改
野性不改 2021-01-02 01:32

Is there an easy way to compute the element-wise sum of N lists in python? I know if we have n lists defined (call the ith list c_i), we can do:

<
相关标签:
2条回答
  • 2021-01-02 02:19

    Just do this:

    [sum(x) for x in zip(*C)]
    

    In the above, C is the list of c_1...c_n. As explained in the link in the comments (thanks, @kevinsa5!):

    * is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call.

    For additional details, take a look at the documentation, under "unpacking argument lists" and also read about calls (thanks, @abarnert!)

    0 讨论(0)
  • 2021-01-02 02:26

    This isn't all that different from Óscar López's answer, but uses itertools.imap instead of a list comprehension.

    from itertools import imap
    list(imap(sum, zip(*C))
    
    0 讨论(0)
提交回复
热议问题