将常量元组值添加到元组列表中
我有一个元组列表(每个元组项是一对整数),我想向列表中的每个元组添加一个常量值。
例如 [(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 numpy,例如,
Use numpy, e.g.,
一如既往,未经测试。 ;-)
如果不需要就地做就更简单了
As always, untested. ;-)
If you don't need to do it in place, it's even simpler
您不能向元组添加常量,因为元组是不可变的。
但是,您可以通过增加旧元组的值来创建新元组。有关如何执行此操作的基础知识,请参阅 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.
一个向元组添加内容的示例,
您可以根据您的要求进行调整
an example to add things to tuple
you can adapt it to your requirement
解决方案:
测试代码:
Solution:
Test code: