Python enumerate() Function: Adding Counters to Iterables
The 'enumerate()' function in Python is used to add a counter to an iterable and return it as an enumerate object. The syntax for the 'enumerate()' function is as follows:
enumerate(iterable, start=0)
where 'iterable' is the object that you want to add a counter to and 'start' is the number from which the counter starts. If 'start' is not provided, it is set to 0 by default.
The 'enumerate()' function returns an iterable object that contains tuples, where each tuple contains the index of the current item and the item itself. Here's an example:
fruits = ['apple', 'banana', 'orange', 'grape']
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 orange
3 grape
In the above example, we use the 'enumerate()' function to add a counter to the 'fruits' list. The 'for' loop then iterates over the enumerate object and prints out the index and the corresponding fruit name.
原文地址: https://www.cveoy.top/t/topic/mw11 著作权归作者所有。请勿转载和采集!