【问题标题】:How to reverse the order of tuples in a list [duplicate]如何反转列表中元组的顺序[重复]
【发布时间】:2021-02-22 14:17:49
【问题描述】:

现在我有如下所示的元组列表:

[(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'

有人知道为什么吗?

【问题讨论】:

  • 所以[(-114, 88), (-90, 88)], ...?
  • i 不是索引,而是元组本身。
  • @Ironkey 是的,这就是我要找的
  • 打印(x[::-1])

标签: python python-3.x


【解决方案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)

【讨论】:

    【解决方案2】:

    您可以使用切片来完成此操作!

    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)]
    

    【讨论】:

      【解决方案3】:

      这里,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 
      

      【讨论】:

        【解决方案4】:
        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] 将反转列表值。

        【讨论】:

        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
        猜你喜欢
        • 1970-01-01
        • 2020-09-07
        • 2016-06-29
        • 2017-12-31
        • 1970-01-01
        • 2020-12-05
        • 2012-09-08
        • 1970-01-01
        • 2012-11-11
        相关资源
        最近更新 更多