【问题标题】:Python adding lists of numbers with other lists of numbersPython将数字列表与其他数字列表添加
【发布时间】:2014-10-27 17:40:11
【问题描述】:

在 Python 中,有没有一种简单的方法可以将列表的各个编号添加到其他列表的各个编号中?在我的代码中,我需要以类似的方式添加大约 10 个长列表:

listOne = [1,5,3,2,7]
listTwo = [6,2,4,8,5]
listThree = [3,2,9,1,1]

因此我希望结果是:

listSum = [10,9,16,11,13]

提前致谢

【问题讨论】:

  • 作为一般规则,最好发布您当前的代码,这样我们就可以知道您尝试了什么、什么不起作用以及为什么它不起作用。
  • 感谢您的提醒

标签: python list sum add


【解决方案1】:

使用 numpy 进行矢量化操作是另一种选择。

>>> import numpy as np
>>> (np.array(listOne) + np.array(listTwo) + np.array(listThree)).tolist()
[10, 9, 16, 11, 13]

对于许多列表来说更简洁:

>>> lists = (listOne, listTwo, listThree)
>>> np.sum([np.array(l) for l in lists], axis=0).tolist()
[10, 9, 16, 11, 13]

注意:每个列表都必须具有相同的维度才能使此方法起作用。否则,您将需要使用此处描述的方法填充数组:https://stackoverflow.com/a/40571482/5060792

为了完整性:

>>> listOne = [1,5,3,2,7]
>>> listTwo = [6,2,4,8,5]
>>> listThree = [3,2,9,1,1]
>>> listFour = [2,4,6,8,10,12,14]
>>> listFive = [1,3,5]

>>> l = [listOne, listTwo, listThree, listFour, listFive]

>>> def boolean_indexing(v, fillval=np.nan):
...     lens = np.array([len(item) for item in v])
...     mask = lens[:,None] > np.arange(lens.max())
...     out = np.full(mask.shape,fillval)
...     out[mask] = np.concatenate(v)
...     return out

>>> boolean_indexing(l,0)
array([[ 1,  5,  3,  2,  7,  0,  0],
       [ 6,  2,  4,  8,  5,  0,  0],
       [ 3,  2,  9,  1,  1,  0,  0],
       [ 2,  4,  6,  8, 10, 12, 14],
       [ 1,  3,  5,  0,  0,  0,  0]])


>>> [x.tolist() for x in boolean_indexing(l,0)]
[[1, 5, 3, 2, 7, 0, 0],
 [6, 2, 4, 8, 5, 0, 0],
 [3, 2, 9, 1, 1, 0, 0],
 [2, 4, 6, 8, 10, 12, 14],
 [1, 3, 5, 0, 0, 0, 0]]

>>> np.sum(boolean_indexing(l,0), axis=0).tolist()
[13, 16, 27, 19, 23, 12, 14]

【讨论】:

    【解决方案2】:

    或者,您也可以使用mapzip,如下所示:

    >>> map(lambda x: sum(x), zip(listOne, listTwo, listThree))
    [10, 9, 16, 11, 13]
    

    【讨论】:

    • 其实map(sum, zip(listOne, listTwo, listThree))就可以了,可以去掉lambda函数。
    • 在 python 3 中,这将返回一个迭代器。
    【解决方案3】:

    使用zipsumlist comprehension

    >>> lists = (listOne, listTwo, listThree)
    >>> [sum(values) for values in zip(*lists)]
    [10, 9, 16, 11, 13]
    

    【讨论】:

    • 非常优雅的解决方案,比我要发布的要好得多!
    • 我不确定,但自从问题发布以来我一直在追平。我做了这个map(sum, zip(*(listOne, listTwo, listThree))) 输出[10, 9, 16, 11, 13] .. 现在我也使用你的代码,输出是[10, 9, 16, 11, 13]不是 [10,10,9,11,13] 我错过了什么??
    • @Grijesh,我没有正确添加我的问题中的数字,那是我的粗心
    • @Adam 没问题我的回答和文森特的回答是一样的。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多