python enumrate函數(shù)的具體使用
基本語法
enumerate(iterable, start=0)
1、iterable: 可迭代對象(列表、元組、字符串等)
2、start: 索引的起始值,默認為0
基本用法
基本遍歷
fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
print(index, value)
輸出:
0 apple
1 banana
2 cherry
指定起始索引
for index, value in enumerate(fruits, start=1):
print(index, value)
輸出
1 apple
2 banana
3 cherry
實際應用場景
需要索引的循環(huán)
for i, item in enumerate(['a', 'b', 'c']):
print(f"第{i+1}個元素是{item}")
輸出
第1個元素是a
第2個元素是b
第3個元素是c
創(chuàng)建字典映射
names = ['Alice', 'Bob', 'Charlie']
name_dict = {i: name for i, name in enumerate(names)}
print(name_dict)
輸出:
{0: 'Alice', 1: 'Bob', 2: 'Charlie'}
處理文件行號
with open('file.txt') as f:
for line_num, line in enumerate(f, start=1):
print(f"{line_num}: {line.strip()}")
與range(len())對比
傳統(tǒng)方式:
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(i, fruits[i])
使用enumerate更簡潔高效:
for i, fruit in enumerate(fruits):
print(i, fruit)
注意事項
1、enumerate返回的是enumerate對象,可以轉換為列表查看:
print(list(enumerate(fruits)))
輸出
[(0, 'apple'), (1, 'banana'), (2, 'cherry')]
2、在Python中,enumerate比手動維護計數(shù)器更Pythonic(更符合Python風格)
3、對于大型迭代,enumerate不會顯著增加內存消耗,因為它也是惰性求值的
到此這篇關于python enumrate函數(shù)的具體使用的文章就介紹到這了,更多相關python enumrate函數(shù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Python創(chuàng)建LNK文件選擇器并導出配置文件
在這篇博客中,我將介紹如何使用Python的wxPython庫開發(fā)一個GUI應用程序,該應用程序可以選擇文件夾中的.lnk(快捷方式)文件,并將選中的文件導出為特定格式的buttons.ini配置文件,需要的朋友可以參考下2025-01-01
使用keras實現(xiàn)Precise, Recall, F1-socre方式
這篇文章主要介紹了使用keras實現(xiàn)Precise, Recall, F1-socre方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

