新聞中心
enumerate函數(shù)用于遍歷序列中的元素以及它們的下標(biāo)。

成都創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)與策劃設(shè)計(jì),桓仁網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:桓仁等地區(qū)?;溉首鼍W(wǎng)站價(jià)格咨詢:18980820575
enumerate函數(shù)說明:
函數(shù)原型:
enumerate(sequence, [start=0])
功能:將可循環(huán)序列sequence以start開始分別列出序列數(shù)據(jù)和數(shù)據(jù)下標(biāo)
即對一個(gè)可遍歷的數(shù)據(jù)對象(如列表、元組或字符串),enumerate會將該數(shù)據(jù)對象組合為一個(gè)索引序列,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)下標(biāo)。
舉例說明:
存在一個(gè)sequence,對其使用enumerate將會得到如下結(jié)果:
start sequence[0] start+1 sequence[1] start+2 sequence[2]......
適用版本:
Python2.3+ Python2.x
注意:在python2.6以后新增了start參數(shù)
英文解釋:
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。
代碼實(shí)例:
enumerate參數(shù)為可遍歷的變量,如 字符串,列表等; 返回值為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')]
在同時(shí)需要index和value值的時(shí)候可以使用 enumerate。
該實(shí)例中,line 是個(gè) 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')) 網(wǎng)頁題目:創(chuàng)新互聯(lián)Python教程:一文搞定Python的enumerate函數(shù)
轉(zhuǎn)載來源:http://m.fisionsoft.com.cn/article/cddsgpi.html


咨詢
建站咨詢
