1. 程式人生 > >這篇文章主要介紹了python中enumerate的用法,對Python初學者而言是非常重要的概念

這篇文章主要介紹了python中enumerate的用法,對Python初學者而言是非常重要的概念

在python中enumerate的用法多用於在for迴圈中得到計數,本文即以例項形式向大家展現python中enumerate的用法。具體如下:


enumerate引數為可遍歷的變數,如 字串,列表等; 返回值為enumerate類。


示例程式碼如下www.97sexsex.com所示:


view sourceprint?1 import string  


2 s = string.ascii_lowercase  


3 e = enumerate(s)  


4 print s  


5 print list(e) 


輸出為:


view sourceprint?1 abcdefghij  


2 [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')] 


在同時需要index和value值的時候可以使用 enumerate。


enumerate應用例項:


該例項中,line 是個 string 包含 0 和 1,要把1都找出來:


方法一:


view sourceprint?1 def read_line(line):  


2   sample = {}  


3   n = len(line)  


4   for i in range(n):  


5     if line[i]!='0':  


6       sample[i] = int(line[i])  


7   return sample 


方法二www.555ni.com:




view sourceprint?1 def xread_line(line):  


2   return((idx,int(val)) for idx, val in enumerate(line) if val != '0')  


3     


4 print read_line('0001110101')  


5 print list(xread_line('0001110101')) 


相信本文示例對大家加深對Python中enumerate的用法能夠起到一定的幫助作用。