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 strings = string.ascii_lowercasee = enumerate(s)print sprint 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函數淺析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林站長站網站的支持!
新聞熱點
疑難解答