簡體   English   中英

Python- For Loop-增加列表中每個元組的每個索引位置

[英]Python- For Loop - Increment each index position for each tuple in list

我在尋找一種可行的方法。 我試圖做一個循環,遍歷我的元組對列表。 每個索引都包含我將計算的數據,並通過每次循環運行將其追加到列表中,直到到達元組列表的末尾。 當前使用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循環增加索引位置?

使用列表理解。 這將迭代列表,將每個元組解壓縮為兩個值ab ,然后從第二個值中減去第一個項目,並將這個新的減去的值插入新的列表中。

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

列表理解是解決此問題的最佳方法,而Malik Brahimi的答案就是解決之道。

不過,堅持使用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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM