我是 Python 的初學者,我試圖了解 for 循環中的迭代是如何工作的。我創建了一個包含整數的多維元組,如下所示image_dimension = ((820, 312), (1500, 500), (2480, 520))現在,我想使用元組每一行的索引作為循環中的索引for。我已經嘗試過代碼for i in image_dimension:,但顯然,它返回每行的元組而不是索引目前我正在使用以下代碼來訪問元組的位置cycles = range(0, 3)for count in cycles: aspect_ratio_x = image_width / image_dimension[count][0] to_crop_from_high_and_low = image_dimension[count][1] * aspect_ratio_x # do other stuff但我不希望使用該range()函數并手動更改其中的元素,而是希望for循環自動迭代元組的行。我知道我可以使用類似的東西cycles = range(0, len(image_dimension)),但我想讓它更干凈
1 回答

Qyouu
TA貢獻1786條經驗 獲得超11個贊
解決方案是使用該enumerate()
函數
for?index,?(i,?j)?in?enumerate(image_dimension): ????aspect_ratio_x?=?image_width?/?image_dimension[index][0] ????to_crop_from_high_and_low?=?image_dimension[index][1]?*?aspect_ratio_x
添加回答
舉報
0/150
提交
取消