Python- For循环 - 增加列表中每个元组的每个索引位置

时间:2015-04-11 12:14:50

标签: 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[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循环增加索引位置吗?

2 个答案:

答案 0 :(得分:4)

使用列表理解。这将迭代列表,将每个元组解包为两个值ab,然后从第二个项中减去第一个项,并将此新的减去值插入新列表中。

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

答案 1 :(得分: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循环来实现相同的目标。使用整数来跟踪当前索引并在循环的每次迭代中将其递增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]