【问题标题】:Python- For Loop - Increment each index position for each tuple in listPython- For Loop - 增加列表中每个元组的每个索引位置
【发布时间】:2015-04-11 12:14:50
【问题描述】:

我一直在寻找一种可能的方法来做到这一点。我正在尝试创建一个循环来遍历我的元组对列表。每个索引都包含我将通过每次循环运行计算并附加到列表中的数据,直到到达元组列表的末尾。目前使用 for 循环,但我可能会使用 while 循环。

index_tuple = [(1, 2), (2, 3), (3, 4)]
total_list = []

for index_pairs in index_tuple:
    total_list.append(index_tuple[0][1] - index_tuple[0][0])    

我想让循环做什么:

(index_tuple[0][1] - index_tuple[0][0])#increment
(index_tuple[1][1] - index_tuple[1][0])#increment
(index_tuple[2][1] - index_tuple[2][0])#increment

那么我想我的最后一个问题是可以使用 while 循环增加索引位置吗?

【问题讨论】:

    标签: python list loops tuples


    【解决方案1】:

    使用列表推导。这会迭代列表,将每个元组解压缩为两个值 ab,然后从第二个项目中减去第一个项目,并将这个减去的新值插入到新列表中。

    totals = [b - a for a, b in index_tuple]
    

    【讨论】:

      【解决方案2】:

      列表推导是解决这个问题的最佳方法,Malik Brahimi's answer 是要走的路。

      尽管如此,坚持您的 for 循环,您需要在循环体中引用 index_pairs,因为在循环迭代时,该变量从 index_tuple 分配给每个元组。您不需要维护索引变量。一个更正的版本是这样的:

      index_tuple = [(1, 2), (2, 3), (3, 4)]
      total_list = []
      
      for index_pairs in index_tuple:
          total_list.append(index_pairs[1] - index_pairs[0])
      
      >>> print total_list
      [1, 1, 1]
      

      将列表中的元组直接解压缩为 2 个变量的更简洁的版本是:

      index_tuples = [(1, 2), (2, 3), (3, 4)]
      total_list = []
      
      for a, b in index_tuples:
          total_list.append(b - a)
      
      >>> print total_list
      [1, 1, 1]
      

      您还询问了如何使用 while 循环来实现相同的目的。使用一个整数来跟踪当前索引,并在循环的每次迭代中将其加一:

      index_tuples = [(1, 2), (2, 3), (3, 4)]
      total_list = []
      
      index = 0
      while index < len(index_tuples):
          total_list.append(index_tuples[index][1] - index_tuples[index][0])
          index += 1
      
      >>> print total_list
      [1, 1, 1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-19
        • 2014-09-29
        • 2022-12-01
        • 2021-11-15
        • 2016-11-02
        • 1970-01-01
        • 2017-08-21
        • 1970-01-01
        相关资源
        最近更新 更多