python sum the values of lists of list

后端 未结 3 2136
说谎
说谎 2020-12-10 07:12

I have list of lists and i need to sum the inner lists, for example,

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

for my case, the len of a[i] is same,

相关标签:
3条回答
  • 2020-12-10 07:17

    A simple answer.

    a = [[1,2,3], [2,1,4], [4,3,6]]
    result = [sum(l) for l in a]
    
    result
    [6, 7, 13]
    
    0 讨论(0)
  • 2020-12-10 07:28

    I know that no one like it but just to give an option:

    result = [reduce(lambda x, y: x+y, l) for l in a]
    
    0 讨论(0)
  • 2020-12-10 07:34
    result = map(sum, a)
    

    Is the way I would do it. Alternatively:

    result = [sum(b) for b in a]
    

    The second variation is the same as yours, except it avoids the unnecessary range statement. In Python, you can iterate over lists directly without having to keep a separate variable as an index.

    0 讨论(0)
提交回复
热议问题