Python 添加列表(或集合,或任何合适的数据类型)的元素

发布于 2024-12-28 11:44:06 字数 274 浏览 3 评论 0原文

有没有一种简单的方法来添加两个大小相等的列表(或元组或任何最有效的数据类型)的成员?

例如,我有 ab 两个元素:

a = (0, 10)
b = (0, -10)

我想添加它们并得到结果:

result = (0, 0)

NOT (0, 10, 0, -10)

Is there an easy way to add the members of two equally sized lists (or tuple or whatever data type would work best)?

I have, for example a and b with 2 elements:

a = (0, 10)
b = (0, -10)

I want to add them and get as result:

result = (0, 0)

NOT (0, 10, 0, -10)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

ゞ记忆︶ㄣ 2025-01-04 11:44:07

您可以使用 numpy 添加列表:

add(array([-1.2, 1.2]), array([1,3]))

及其结果:

array([-0.2, 4.2])

You can use numpy to add the lists:

add(array([-1.2, 1.2]), array([1,3]))

and the result it:

array([-0.2, 4.2])
冷默言语 2025-01-04 11:44:06

您可以在 Python 中用一行完成此操作:

map(sum, zip(A, B))

示例:

>>> B = [1, 2, 3, 4]
>>> C = [1, 2, 4, 8]
>>> map(sum, zip(B, C))
[2, 4, 7, 12]

You can do this in one line in Python:

map(sum, zip(A, B))

Example:

>>> B = [1, 2, 3, 4]
>>> C = [1, 2, 4, 8]
>>> map(sum, zip(B, C))
[2, 4, 7, 12]
无人问我粥可暖 2025-01-04 11:44:06

三个选项:

>>> [a+b for (a,b) in zip(A,B)]
>>> map(int.__add__, A, B)
>>> map(sum, zip(A,B))

Three options:

>>> [a+b for (a,b) in zip(A,B)]
>>> map(int.__add__, A, B)
>>> map(sum, zip(A,B))
拧巴小姐 2025-01-04 11:44:06

如果你想使用数字列表进行操作,请使用 numpy

>>> a = [1,2]
>>> b = [1,2]
>>> import numpy as np
>>> np.add(a,b)
array([2, 4])
>>> 

if you want to operate with list of numbers use numpy

>>> a = [1,2]
>>> b = [1,2]
>>> import numpy as np
>>> np.add(a,b)
array([2, 4])
>>> 
奶茶白久 2025-01-04 11:44:06
List ANSWER = ()
for index in range(0, len(A))
  ANSWER.append(A[index]+B[index])
List ANSWER = ()
for index in range(0, len(A))
  ANSWER.append(A[index]+B[index])
墨落成白 2025-01-04 11:44:06

是的,只需这样做

map(sum,zip(A,B)

,或者(实际上明显更快)

u=map(lambda a,b:a+b,A,B)

计时示例:

A=range(3000)
B=range(3000)
for i in range(15000):
 u=map(lambda a,b:a+b,A,B)   # takes about 7.2 seconds
 # u=map(sum,zip(A,B))       # takes about 11 seconds
 # u=map(int.__add__,A,B) # (Edward Loper) actually also consistently ~0.5 sec slower than lambda

yes, just do this

map(sum,zip(A,B)

or, (actually clearly faster)

u=map(lambda a,b:a+b,A,B)

Timing examples:

A=range(3000)
B=range(3000)
for i in range(15000):
 u=map(lambda a,b:a+b,A,B)   # takes about 7.2 seconds
 # u=map(sum,zip(A,B))       # takes about 11 seconds
 # u=map(int.__add__,A,B) # (Edward Loper) actually also consistently ~0.5 sec slower than lambda
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文