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

創(chuàng)新互聯(lián)公司是一家朝氣蓬勃的網(wǎng)站建設(shè)公司。公司專注于為企業(yè)提供信息化建設(shè)解決方案。從事網(wǎng)站開發(fā),網(wǎng)站制作,網(wǎng)站設(shè)計(jì),網(wǎng)站模板,微信公眾號(hào)開發(fā),軟件開發(fā),小程序設(shè)計(jì),10年建站對(duì)木屋等多個(gè)行業(yè),擁有多年設(shè)計(jì)經(jīng)驗(yàn)。
enumerate函數(shù)說明:
函數(shù)原型:enumerate(sequence, [start=0])
功能:將可循環(huán)序列sequence以start開始分別列出序列數(shù)據(jù)和數(shù)據(jù)下標(biāo)
即對(duì)一個(gè)可遍歷的數(shù)據(jù)對(duì)象(如列表、元組或字符串),enumerate會(huì)將該數(shù)據(jù)對(duì)象組合為一個(gè)索引序列,同時(shí)列出數(shù)據(jù)和數(shù)據(jù)下標(biāo)。
舉例說明:
存在一個(gè)sequence,對(duì)其使用enumerate將會(huì)得到如下結(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)
輸出結(jié)果
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://fisionsoft.com.cn/article/dpjceeh.html


咨詢
建站咨詢
