python for enumerate 遍历数组 To iterate over a Python array or list with both the index and the value of each item, you can use the enumerate() function in a for loop
Published on Aug. 22, 2023, 12:14 p.m.
To iterate over a Python array or list with both the index and the value of each item, you can use the enumerate() function in a for loop. Here is an example:
my_list = ['apple', 'banana', 'orange']
for idx, value in enumerate(my_list):
print(idx, value)
This will output:
0 apple
1 banana
2 orange
In this example, we’re using the enumerate() function to loop over my_list and get both the index and the value of each item. The idx variable will hold the index of the current item (starting from 0), and the value variable will hold the value of the current item.
You can use this technique with any Python array or list to iterate over both the index and value of each item.
python for enumerate 配合tqdm
If you want to use enumerate() with the tqdm library to get a progress bar while iterating over the array or list, you can use the tqdm() function as a wrapper around enumerate(). Here is an example:
from tqdm import tqdm
my_list = ['apple', 'banana', 'orange']
for idx, value in tqdm(enumerate(my_list), total=len(my_list)):
print(idx, value)
In this example, we’re using the tqdm() function as a wrapper around enumerate(my_list) to get a progress bar while looping over my_list. The total argument tells tqdm how many iterations there will be in total. You can also specify other parameters to customize the appearance of the progress bar.
Note that if you’re using tqdm() with a large array or list, it may slow down the iteration because it has to update the progress bar on every iteration. In this case, you may want to use a chunked iteration approach or use tqdm() with a lower mininterval parameter to update the progress bar less frequently.
python for enumerate 配合tqdm 和zip
To use enumerate() and zip() with tqdm in Python, you can simply wrap them in a tqdm() function call. Here is an example:
from tqdm import tqdm
my_list_1 = ['apple', 'banana', 'orange']
my_list_2 = ['red', 'yellow', 'orange']
for idx, (value_1, value_2) in tqdm(enumerate(zip(my_list_1, my_list_2)), total=len(my_list_1)):
print(idx, value_1, value_2)
In this example, we have two arrays (my_list_1 and my_list_2), and we’re zipping them together so that we can iterate over them in parallel. The enumerate() function is then used to get the index of each pair of values.
We then wrap the enumerate() and zip() functions in a tqdm() function call to get a progress bar while iterating over the pairs. The total argument of tqdm is set to the length of my_list_1 so that the progress bar is accurate.
Note that the order of parameters to enumerate() and zip() is important in this example, since we want to enumerate over the zipped pairs, not zip over the enumerated pairs.