Python-For循环-增加列表中每个元组的每个索引位置
我到处寻找一种可能的方法来做这件事。我正在尝试做一个循环,它将遍历我的元组对列表。每个索引包含我将通过每次循环运行计算并附加到列表中的数据,直到到达元组列表的末尾。当前正在使用for循环,但我可能会使用while循环Python-For循环-增加列表中每个元组的每个索引位置,python,list,loops,tuples,Python,List,Loops,Tuples,我到处寻找一种可能的方法来做这件事。我正在尝试做一个循环,它将遍历我的元组对列表。每个索引包含我将通过每次循环运行计算并附加到列表中的数据,直到到达元组列表的末尾。当前正在使用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
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循环来增加索引位置?使用列表理解。这将迭代列表,将每个元组解压为两个值
a
和b
,然后从第二个项目中减去第一个项目,并将这个新的减去值插入新列表
totals = [b - a for a, b in index_tuple]
使用列表理解。这将迭代列表,将每个元组解压为两个值
a
和b
,然后从第二个项目中减去第一个项目,并将这个新的减去值插入新列表
totals = [b - a for a, b in index_tuple]
列表理解是解决这个问题的最佳方法,也是一条出路 然而,坚持for循环,您需要在循环体中引用
index\u对
,因为当循环迭代时,这个变量被分配给index\u 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循环来实现相同的功能。使用整数跟踪当前索引,并在循环的每次迭代中将其递增1:
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]
index_tuples=[(1,2)、(2,3)、(3,4)]
总清单=[]
索引=0
而index>>打印总清单
[1, 1, 1]
列表理解是解决此问题的最佳方法,也是一条可行之路
然而,坚持for循环,您需要在循环体中引用index\u对
,因为当循环迭代时,这个变量被分配给index\u 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循环来实现相同的功能。使用整数跟踪当前索引,并在循环的每次迭代中将其递增1:
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]
index_tuples=[(1,2)、(2,3)、(3,4)]
总清单=[]
索引=0
而index>>打印总清单
[1, 1, 1]