[英]Iterate into a multidimensional tuple with for loop
I'm a beginner in Python and I'm trying to understand how the iterations in for loop work.我是 Python 的初学者,我试图了解 for 循环中的迭代是如何工作的。
I have created a multidimensional tuple that contains integer like below我创建了一个包含如下整数的多维元组
image_dimension = ((820, 312),
(1500, 500),
(2480, 520))
Now, I would like to use the index of every row of the tuple as an index in a for
cycle.现在,我想使用元组每一行的索引作为for
循环中的索引。
I have tried the code for i in image_dimension:
but clearly, it returns the tuple of every row and not the index我已经for i in image_dimension:
尝试了for i in image_dimension:
的代码for i in image_dimension:
但很明显,它返回每一行的元组而不是索引
At the moment I'm using the following code to access the positions of the tuple目前我正在使用以下代码访问元组的位置
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
but instead of using the range()
function and manually change the element inside it, I would like the for
loop automatically iterate the row of the tuple.但不是使用range()
函数并手动更改其中的元素,我希望for
循环自动迭代元组的行。
I know I could use something like cycles = range(0, len(image_dimension))
but I would like to make it cleaner我知道我可以使用cycles = range(0, len(image_dimension))
但我想让它更干净
As suggested by @alani the solution is to use the enumerate()
function正如@alani 所建议的,解决方案是使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.