简体   繁体   English

在 python 中的 for 循环期间保存迭代次数

[英]Save iteration number during a for loop in python

I have a list of arrays that I am iterating over with python, so the head of my loop looks like:我有一个 arrays 列表,我正在用 python 进行迭代,所以我的循环头看起来像:

for item in my_long_list:
     do_something

My problem is that I want to save the iteration number, so that info can be extracted from another array, something like:我的问题是我想保存迭代次数,以便可以从另一个数组中提取信息,例如:

for item in my_long_list:
    do_something
    grab_values(another_long_list[i])

where i is he iteration number that the loop is going through at that moment. i是那个时候循环正在经历的迭代次数。

I thought about doing a nested loop like:我想过做一个嵌套循环,如:

for i in list(range(1,len(my_long_list)):
    for item in my_long_list:
        do_something
        grab_values(another_long_list[i])

but it repeats i for each one of the items , when in reality what I want is one single iteration number per item in my long list.但它对每个items重复i ,而实际上我想要的是我长列表中每个项目的一个迭代次数。

So is there a way to "store" the iteration number and use it within the loop with python?那么有没有办法“存储”迭代号并在 python 的循环中使用它?

You can use the enumerate method that returns the tuple of item number and value.您可以使用返回项目编号和值的元组的enumerate方法。

for iter, i in enumerate(my_long_list)):
    for item in my_long_list:
        do_something
        grab_values(another_long_list[iter])

if you want current item number, maybe you can do this:如果你想要当前的项目编号,也许你可以这样做:

for i, v in enumerate(my_long_list,1): # item number from 1 start
    do_something
    grab_values(another_long_list[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM