程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Specific usage of enumeration function enumerate() in Python

編輯:Python

Compared with range,list And so on ,enumerate It's not easy to use just by shape . in fact ,enumerate It still works .

enumerate() yes python Built in functions for 、 Apply to python2.x and python3.x

enumerate In the dictionary is enumeration 、 List means

enumerate The parameter is ergodic / Objects that can be iterated ( As listing 、 character string )

enumerate It's mostly used in for Count in the loop , Use it to get both index and value , That is to say index and value Value can be used enumerate

enumerate() Back to a enumerate object

python The most common data structure in is list, Handle list Each element in , Usually for Cycle through .

We see first , Joined the enumerate after ,list The change of :

One more index , At the same time, it can read the elements . What's the use of this feature ? Look at a piece of code :

ls = ['a', 'b', 'c']# method 1for i in range(len(ls)): print(i, end=' ') print(ls[i])# method 2for s in ls: print(ls.index(s), end=' ') print(s)# method 3for i, s in enumerate(ls): print(i, end=' ') print(s)

Look at the way 3 You can access the index more easily i And the corresponding elements s.

and , use enumerate It will make the code more advanced ~

enumerate Use :

for example : It is known that lst = [1,2,3,4,5,6], Request output :

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# Specify index from 1 Start >>> 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# Specify index from 3 Start >>> for index,value in enumerate(lst,3):print ('%s,%s' % (index,value))3,14,25,36,47,58,6 Add :

If you want to count the number of lines in the file , It can be written like this :

count = len(open(filepath, 'r').readlines())

This method is simple , But it can be slow , It doesn't even work when the file is large .

You can use enumerate():

count = 0for index, line in enumerate(open(filepath,'r')): count += 1

This is about Python Enumeration function in enumerate() This is the end of the article on the specific usage of , More about Python enumerate Please search the previous articles of software development network or continue to browse the relevant articles below. I hope you will support software development network more in the future !



  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved