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函數淺析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
