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

創(chuàng)新互聯(lián)公司是一家朝氣蓬勃的網(wǎng)站建設(shè)公司。公司專注于為企業(yè)提供信息化建設(shè)解決方案。從事網(wǎng)站開發(fā),網(wǎng)站制作,網(wǎng)站設(shè)計,網(wǎng)站模板,微信公眾號開發(fā),軟件開發(fā),小程序設(shè)計,10年建站對木屋等多個行業(yè),擁有多年設(shè)計經(jīng)驗。
enumerate函數(shù)說明:
函數(shù)原型:enumerate(sequence, [start=0])
功能:將可循環(huán)序列sequence以start開始分別列出序列數(shù)據(jù)和數(shù)據(jù)下標(biāo)
即對一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串),enumerate會將該數(shù)據(jù)對象組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標(biāo)。
舉例說明:
存在一個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。
代碼實例:
enumerate參數(shù)為可遍歷的變量,如 字符串,列表等; 返回值為enumerate類。
import string s = string.ascii_lowercase e = enumerate(s) print s print list(e)
輸出結(jié)果
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')) 當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python小白福利之enumerate函數(shù)
當(dāng)前網(wǎng)址:http://m.5511xx.com/article/dpjceeh.html


咨詢
建站咨詢
