enumerate() 函數(shù)用于同時遍歷索引和元素,常用于循環(huán)中。這個函數(shù)返回一個包含索引和元素的元組,可以通過解包的方式獲取它們。
使用方法:
enumerate(iterable, start=0)
.
- iterable: 要遍歷的可迭代對象。
- start: 索引起始值,默認(rèn)為 0。
示例說明:
# 示例列表
fruits = ['apple', 'banana', 'orange', 'grape']
# 使用 enumerate 遍歷列表的索引和元素
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
輸出:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: orange
Index: 3, Fruit: grape
在上面的示例中,enumerate(fruits) 返回一個可迭代對象,每次迭代都產(chǎn)生包含索引和元素的元組。文章來源:http://www.zghlxwxcb.cn/news/detail-795959.html
我們使用 for 循環(huán)和解包操作獲取這兩個值,然后進(jìn)行打印。文章來源地址http://www.zghlxwxcb.cn/news/detail-795959.html
到了這里,關(guān)于Python:enumerate() 函數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!