for enumerate
时间: 2023-11-01 12:00:59 浏览: 45
enumerate函数用于在迭代过程中同时获得元素的索引和值。它返回一个可迭代对象,其中每个元素都是一个包含索引和对应值的元组。通过使用enumerate函数,可以方便地在for循环中同时遍历索引和值。
下面是一个示例:
```python
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(index, fruit)
```
输出结果为:
```
0 apple
1 banana
2 orange
```
在这个例子中,每个元素都是一个包含索引和对应水果的元组。通过使用enumerate函数,我们可以在for循环中直接获取索引和值,并进行相应的操作。
相关问题
python for enumerate
enumerate() 函数是 Python 内置函数之一,它可以将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环中。例如:
```
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
print(index, fruit)
```
输出结果为:
```
0 apple
1 banana
2 orange
```
for in enumerate
'for in enumerate' is a Python loop statement that allows you to iterate over an iterable while also keeping track of the current index of each element. Here's an example usage:
```python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
```
Output:
```
0 apple
1 banana
2 cherry
```
In this example, `enumerate(fruits)` returns an iterator that produces tuples containing the index and the corresponding fruit from the `fruits` list. The `for` loop then iterates over each tuple, unpacking it into the variables `index` and `fruit`, and prints them out.