简体   繁体   English

Python:如何修改列表中的元组?

[英]Python: how to revise tuples in an list?

I have a list of x,y tuples. 我有一个x,y元组的列表。 Think of these original tuples as being a change in x and y. 将这些原始元组视为x和y的变化。 I wish to apply these subsequent changes in x and y to the previous tuple. 我希望将x和y中的这些后续更改应用于上一个元组。 For ex, after the zero term, x gained 100 and y stayed the same. 例如,在零项之后,x增加了100,y保持不变。 Thus the new first term would be (100,100). 因此,新的第一项将是(100,100)。 After that, x stayed the same and y decreased by 100. Applying that to the revised first term would result in a revised second term of (100,0) and etc. 之后,x保持不变,y减少100。将其应用于修订的第一项将导致修订的第二项(100,0)等。

xy = [(0,100), (100,0), (0,-100), (-100,0)]

This is the desired result: 这是期望的结果:

xy = [(0,100), (100,100), (100,0), (0,0)]

How to work around the immutabilty of lists? 如何解决列表的不变性? How do I get this done in a loop? 如何循环完成此操作?

The list itself is still mutable; 该列表本身仍然可变。 just replace the tuples with new ones: 只需用新的替换元组:

x, y = 0, 0
for i, (dx, dy) in enumerate(xy):
    x += dx
    y += dy
    xy[i] = (x, y)

Demo: 演示:

>>> xy = [(0, 100), (100, 0), (0, -100), (-100, 0)]
>>> x, y = 0, 0
>>> for i, (dx, dy) in enumerate(xy):
...     x += dx
...     y += dy
...     xy[i] = (x, y)
... 
>>> xy
[(0, 100), (100, 100), (100, 0), (0, 0)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM