python enumerate
时间: 2023-09-27 12:08:21 浏览: 107
python enumerate用法总结
The `enumerate()` function in Python is used to associate an index with each element of an iterable. It returns an enumerate object which contains tuples of the form `(index, element)` for each element in the iterable.
Syntax:
```python
enumerate(iterable, start=0)
```
Parameters:
- `iterable`: an iterable object (list, tuple, string, etc.) whose elements need to be enumerated.
- `start`: (optional) the starting index of the enumeration. Default value is `0`.
Example:
```python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
```
Output:
```
0 apple
1 banana
2 cherry
```
In the above example, the `enumerate()` function is used to associate an index with each fruit in the `fruits` list. The resulting enumerate object is then iterated over using a for loop, and the index and fruit values are printed for each iteration.
阅读全文