熱線電話:13121318867

登錄
首頁精彩閱讀python遍歷序列enumerate函數淺析
python遍歷序列enumerate函數淺析
2018-04-22
收藏

python遍歷序列enumerate函數淺析

enumerate函數用于遍歷序列中的元素以及它們的下標。
enumerate函數說明:
函數原型:enumerate(sequence, [start=0])
功能:將可循環序列sequence以start開始分別列出序列數據和數據下標
即對一個可遍歷的數據對象(如列表、元組或字符串),enumerate會將該數據對象組合為一個索引序列,同時列出數據和數據下標。

舉例說明:
存在一個sequence,對其使用enumerate將會得到如下結果:
start        sequence[0]
start+1  sequence[1]
start+2    sequence[2]......
適用版本:
Python2.3+
Python2.x
注意:在python2.6以后新增了start參數
英文解釋:
Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence。
代碼實例:
enumerate參數為可遍歷的變量,如 字符串,列表等; 返回值為enumerate類。
    
import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)

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

在同時需要index和value值的時候可以使用 enumerate。
該實例中,line 是個 string 包含 0 和 1,要把1都找出來:    
def xread_line(line):
 return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
print read_line('0001110101')
print list(xread_line('0001110101'))
總結
以上所述是小編給大家介紹的python遍歷序列enumerate函數淺析,希望對大家有所幫助

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢