Python List in List麻烦

Python List in List trouble

在开始之前告诉我的问题抱歉我的语法和英语不是很好。我是 Python 学习者。今天我正在做一个项目,但遇到了麻烦。我正在尝试循环。

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7`],[1,2]]

这是我的列表,我正在尝试创建一个循环。该循环将从彼此减去每个第一个值,并且每隔几秒减去几秒然后打印。让我更简单地解释一下我的麻烦。 [[x,y][x1,y1][x2,y2] 我需要减去 x1-x 然后在 x2-x1 之后打印结果然后打印结果但同时打印 y1-y 然后打印所以控制台输出应该是这样的;

1,1
1,2
2,1...

我试过的方法

while True:
for x,y in coordinates:
    x = x - y
    print(x)

这不起作用,因为它将 x 值减去 y 值。我知道这太不对了。

我在互联网上进行了研究,但我不是很了解这个主题。 我正在寻求帮助。谢谢大家。

一个简单而天真的实现

def pr(arr):
    i = 1
    while i < len(arr):
        (x,y) = arr[i]
        (a,b) = arr[i-1]
        print(x-a, y-b)
        i += 1


if __name__ == '__main__':
    coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7],[1,2]]
    pr(coordinates)

O/P:

1 1
1 2
2 1
2 1
-6 -5

您需要使用 range 函数遍历 list,以便您可以同时获得当前和下一个。所以你可以在循环中做减法。

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7],[1,2]]
for i in range(len(coordinates) - 1):
    print(coordinates[i+1][0] - coordinates[i][0], coordinates[i+1][1] - coordinates[i][1])

这与您的原始代码非常相似:

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7`],[1,2]]
x_prev = None
for x, y in coordinates:
    if x_prev is not None:
        print('{}, {}'.format(x - x_prev, y - y_prev)
    x_prev, y_prev = x, y

如果你想概括一点,对于不同长度的坐标,你可以这样做:

coordinates = [[1,2],[2,3],[3,5],[5,6],[7,7`],[1,2]]
prev = None
for c in coordinates:
    if prev is not None:
        print(', '.join(c2-c1 for c1, c2 in zip(prev, c)))
    prev = c