網站首頁 編程語言 正文
相比于range,list等簡易單詞,enumerate僅憑外形都不太讓人愿意用。事實上,enumerate還是很好用的。
- enumerate()是python的內置函數、適用于python2.x和python3.x
- enumerate在字典上是枚舉、列舉的意思
- enumerate參數為可遍歷/可迭代的對象(如列表、字符串)
- enumerate多用于在for循環中得到計數,利用它可以同時獲得索引和值,即需要index和value值的時候可以使用enumerate
- enumerate()返回的是一個enumerate對象
python中最常用的數據結構就是list,處理list中每個元素,通常都用for循環搞定。
我們先看,加入了enumerate之后,list的變化:
多了一個索引,同時還能讀取到元素。這個特性有什么應用呢?看一段代碼:
ls = ['a', 'b', 'c']
# method 1
for i in range(len(ls)):
print(i, end=' ')
print(ls[i])
# method 2
for s in ls:
print(ls.index(s), end=' ')
print(s)
# method 3
for i, s in enumerate(ls):
print(i, end=' ')
print(s)
一看方法3就能更簡便地訪問到索引i和對應的元素s。
而且,用enumerate會顯得代碼更加高級~
enumerate的使用:
例如:已知lst = [1,2,3,4,5,6],要求輸出:
0,1
1,2
2,3
3,4
4,5
5,6
>>> lst = [1,2,3,4,5,6]
>>> for index,value in enumerate(lst):
? print ('%s,%s' % (index,value))
??
0,1
1,2
2,3
3,4
4,5
5,6
#指定索引從1開始
>>> lst = [1,2,3,4,5,6]
>>> for index,value in enumerate(lst,1):
print ('%s,%s' % (index,value))
1,1
2,2
3,3
4,4
5,5
6,6
#指定索引從3開始
>>> for index,value in enumerate(lst,3):
print ('%s,%s' % (index,value))
3,1
4,2
5,3
6,4
7,5
8,6
補充:
如果要統計文件的行數,可以這樣寫:
count = len(open(filepath, 'r').readlines())
這種方法簡單,但是可能比較慢,當文件比較大時甚至不能工作。
可以利用enumerate():
count = 0
for index, line in enumerate(open(filepath,'r')):
count += 1
原文鏈接:https://blog.csdn.net/leviopku/article/details/99947589
相關推薦
- 2022-10-23 C#中new操作符的工作機制_C#教程
- 2022-09-18 Go語言實現服務端消息接收和發送_Golang
- 2022-10-15 Windows10搭建FTP服務器詳細教程_FTP服務器
- 2022-09-29 Python組合數據類型詳解_python
- 2022-10-19 Android?webview加載H5方法詳細介紹_Android
- 2022-07-12 解決錯誤:Cannot resolve symbol ‘JdbcTemplate‘
- 2022-08-07 pandas時間序列之pd.to_datetime()的實現_python
- 2022-07-11 atom插件之·atom-minify配置支持壓縮es6
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支