现在我有元组列表,如下所示:
[(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]
我当前的代码如下:
i = 13 # Let i start at index 13
tech = [] # Define list
while (x, y) != (start_x, start_y): # while loop to iterate through all the coordinates until the path has been found
tech.append(solution[x,y]) # Appends the coordinates to tech list
x, y = solution[x, y] # get x and y coordinates
for i in tech: # Loop thorugh each tuple
print(i) # Print each tuple
# time.sleep(1)
i -= 1 # Decrement the index
我想做的是以相反的顺序打印列表,从最后的元组坐标在前面,第一个元组坐标在后面。现在的问题是,当我尝试减少索引时会引发此错误:
unsupported operand type(s) for -=: 'tuple' and 'int'
有人知道为什么吗?
答案 0 :(得分:1)
您可以通过以下方式使用.reverse()
函数:
data= [(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64),
(6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]
data.reverse()
print(data)
答案 1 :(得分:1)
您可以使用切片来完成此操作!
x = [(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]
print(x[::-1])
输出
[(-114, 88), (-90, 88), (-66, 88), (-66, 64), (-42, 64), (-18, 64), (6, 64), (30, 64), (30, 40), (30, 16), (30, -8), (30, -32), (54, -32), (78, -32)]
答案 2 :(得分:0)
在这里,i
是用于迭代tech
列表的变量,因此,如果要向后打印项目,则将每个元组减1都不起作用。
print(*reversed(tech),sep="\n")
就地反向:-)
tech.reverse()
还是在每次迭代中使用不同的变量(您的意图是减少i
?)
for x in tech: # Loop thorugh each tuple
print(x) # Print each tuple
# time.sleep(1)
i -= 1 # Decrement the index
答案 3 :(得分:0)
l = [(78, -32), (54, -32), (30, -32), (30, -8), (30, 16), (30, 40), (30, 64), (6, 64), (-18, 64), (-42, 64), (-66, 64), (-66, 88), (-90, 88), (-114, 88)]
print(l[::-1])
使用[::-1]
将反转列表值。