【问题标题】:How to add up 2 list elements to form a new list in python, by one shot? [duplicate]python - 如何一次将2个列表元素相加以在python中形成一个新列表? [复制]
【发布时间】:2017-05-09 19:17:09
【问题描述】:

我定义了 2 个列表,n1 和 n2:

In [1]: n1=[1,2,3]

In [2]: n2=[4,5,6]

In [3]: n1+n2
Out[3]: [1, 2, 3, 4, 5, 6]

In [4]: n1+=n2

In [5]: n1
Out[5]: [1, 2, 3, 4, 5, 6]

好吧,我期望做的是得到一个新列表: n3=[5,7,9] 作为 n1 和 n2 中每个元素的汇总。

我不想写一个 for 循环来完成这个日常工作。 python 运算符或库是否支持一次性调用来执行此操作?

【问题讨论】:

标签: python list loops for-loop summary


【解决方案1】:
[x + y for x, y in zip(n1, n2)]
[n1[i] + n2[i] for i in range(len(n1))]
map(int.__add__, n1, n2)

【讨论】:

  • 这个太棒了。
【解决方案2】:

我不想编写一个 for 循环来完成这项日常工作。 python 运算符或库是否支持一次性调用来执行此操作?

Python 本身不支持,但是可以使用库NumPy

import numpy as np

n1 = np.array([1, 2, 3])
n2 = np.array([4, 5, 6])

n3 = n1 + n2

或者,您可以使用list comprehensionzip()

n3 = [x + y for x, y in zip(n1, n2)]

【讨论】:

    【解决方案3】:

    不,没有一次性的命令。在两个列表中添加元素不是常见的操作。你无法避免这里的循环。

    使用zip()list comprehension

    [a + b for a, b in zip(n1, n2)]
    

    或者,使用numpy 数组:

    from numpy import array
    
    n3 = array(n1) + array(n2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 2018-05-20
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2022-10-31
      相关资源
      最近更新 更多