将常量元组值添加到元组列表中

发布于 2024-08-22 23:35:48 字数 164 浏览 4 评论 0原文

我有一个元组列表(每个元组项是一对整数),我想向列表中的每个元组添加一个常量值。

例如 [(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]

xk,yk 是常量

我该怎么做

谢谢

I have a list of tuples (each tuple item is a pair of integers) and I would like to add a constant value to each tuple in the list.

For example
[(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]

xk,yk are constants

How do I do this

Thanks

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

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

发布评论

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

评论(5

一花一树开 2024-08-29 23:35:48

使用 numpy,例如,

>>> import numpy as np
>>> a = np.array([[1,2],[2,3]])
>>> print a
[[1 2]
 [2 3]]
>>> print a + 2
[[3 4]
 [4 5]]

Use numpy, e.g.,

>>> import numpy as np
>>> a = np.array([[1,2],[2,3]])
>>> print a
[[1 2]
 [2 3]]
>>> print a + 2
[[3 4]
 [4 5]]
走过海棠暮 2024-08-29 23:35:48
>>>> l = [(1,2), (3,4)]
>>>> for i, e in enumerate(l):
....     l[i] = (e[0]+xk, e[1]+yk)

一如既往,未经测试。 ;-)

如果不需要就地做就更简单了

>>>> l = [(e[0]+xk, e[1]+yk) for e in l]
>>>> l = [(1,2), (3,4)]
>>>> for i, e in enumerate(l):
....     l[i] = (e[0]+xk, e[1]+yk)

As always, untested. ;-)

If you don't need to do it in place, it's even simpler

>>>> l = [(e[0]+xk, e[1]+yk) for e in l]
得不到的就毁灭 2024-08-29 23:35:48

您不能向元组添加常量,因为元组是不可变的。

但是,您可以通过增加旧元组的值来创建新元组。有关如何执行此操作的基础知识,请参阅 jae 的答案。

但您应该注意,您将在此循环中创建大量新元组,这可能不是处理此问题的非常有效的方法。您应该研究 numpy (如 nikow 建议的那样)或者使用列表或坐标对象而不是元组。

You can't add a constant to a tuple because tuples are immutable.

You can however create a new tuple from the old one by incrementing it's values. See jae's answer for the basics of how to do this.

You should note however that you will be creating a lot of new tuples in this loop and this may not be a very efficient way of handling this. You should investigate numpy (as suggested by nikow) or perhaps using lists or coordinate objects instead of tuples.

断爱 2024-08-29 23:35:48

一个向元组添加内容的示例,

>>> a=(1,2)
>>> a+=(1,)
>>> a
(1, 2, 1)

您可以根据您的要求进行调整

an example to add things to tuple

>>> a=(1,2)
>>> a+=(1,)
>>> a
(1, 2, 1)

you can adapt it to your requirement

只为守护你 2024-08-29 23:35:48

解决方案:

l = [(i[0]+k[0], i[1]+k[1]) for i in l]

测试代码:

l = [(1,2), (3,4)]
k = (10, 100)
l = [(i[0]+k[0], i[1]+k[1]) for i in l]
assert l == [(11, 102), (13, 104)]

Solution:

l = [(i[0]+k[0], i[1]+k[1]) for i in l]

Test code:

l = [(1,2), (3,4)]
k = (10, 100)
l = [(i[0]+k[0], i[1]+k[1]) for i in l]
assert l == [(11, 102), (13, 104)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文