Python中enumerate用法詳解

來源:互聯網
上載者:User

標籤:lin   for迴圈   用法   div   輸出   for   color   檔案的   rate   

enumerate()是python的內建函數、適用於python2.x和python3.x
enumerate在字典上是枚舉、列舉的意思
enumerate參數為可遍曆/可迭代的對象(如列表、字串)
enumerate多用於在for迴圈中得到計數,利用它可以同時獲得索引和值,即需要index和value值的時候可以使用enumerate
enumerate()返回的是一個enumerate對象

>>> lst = [1, 2, 3, 4, 10, 5]>>> enumerate(lst)<enumerate object at 0x00000000032A3990>

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,11,22,33,44,55,6
#指定索引從1開始>>> lst = [1,2,3,4,5,6]>>> for index,value in enumerate(lst,1):print (‘%s,%s‘ % (index,value))1,12,23,34,45,56,6#指定索引從3開始>>> for index,value in enumerate(lst,3):print (‘%s,%s‘ % (index,value))3,14,25,36,47,58,6

補充:
如果要統計檔案的行數,可以這樣寫:
count = len(open(filepath, ‘r‘).readlines())
這種方法簡單,但是可能比較慢,當檔案比較大時甚至不能工作。

可以利用enumerate():
count = 0
for index, line in enumerate(open(filepath,‘r‘)):
   count += 1

參考資料:
python enumerate用法總結: http://blog.csdn.net/churximi/article/details/51648388

Python中enumerate用法詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.