【问题标题】:how to sum lists in lists pairwise in python and put this sum in a new list [duplicate]如何在python中成对地对列表中的列表求和并将这个总和放入一个新列表中[重复]
【发布时间】:2014-09-23 21:59:48
【问题描述】:

问题很清楚,但举个例子:

a = [[1,2],[3,4],[5,6],[7,8]]

那么我要列出的清单是:

a_new = [ 1+3+5+7 , 2+4+6+8]

列表中的列表始终具有相同的长度,当然我不仅希望对二维这样做,而且对大数字 n 也这样做。

到目前为止,我已经尝试过使用双循环,但完全失败了,非常感谢您的帮助。

【问题讨论】:

  • 调试和实现问题不在 Programmers.SE 上的主题,最好在 StackOverflow 上提问(如 help center 中所述)。
  • 好的,谢谢迈克尔,我没有意识到这一点

标签: python


【解决方案1】:

使用zip() function 将输入列表从行转换为列,然后使用sum() 这些列:

[sum(col) for col in zip(*a)]

演示:

>>> a = [[1,2],[3,4],[5,6],[7,8]]
>>> zip(*a)
[(1, 3, 5, 7), (2, 4, 6, 8)]
>>> [sum(col) for col in zip(*a)]
[16, 20]

【讨论】:

    【解决方案2】:

    使用地图:

    >>> a = [[1,2],[3,4],[5,6],[7,8]]
    >>> map(sum, zip(*a))
    [16, 20]
    >>>
    

    【讨论】:

    • 考虑到在 Python 3 中 map() 返回的是一个迭代器,而不是一个列表。
    【解决方案3】:

    这里没有使用map()zip()reduce(),而是使用列表连接的纯列表理解方法:

    [sum([x for x, y in a])]+[sum([y for x, y in a])]
    

    >>> a = [[1,2],[3,4],[5,6],[7,8]]
    >>> a_new = [sum([x for x, y in a])]+[sum([y for x, y in a])]
    >>> a_new
    [16, 20]
    >>> 
    

    【讨论】:

    • 这个解决方案不会随着更多的列而扩展。
    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 2014-05-18
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多