enumerate函數(shù)用于遍歷序列中的元素以及它們的下標(biāo)。
enumerate函數(shù)說明:
enumerate()是python的內(nèi)置函數(shù)
enumerate在字典上是枚舉、列舉的意思
函數(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。
代碼實(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')]
在同時需要index和value值的時候可以使用 enumerate。
該實(shí)例中,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'))
如果對一個列表,既要遍歷索引又要遍歷元素時,首先可以這樣寫:
list1 = ["這", "是", "一個", "測試"] for i in range (len(list1)): print i ,list1[i]
上述方法有些累贅,利用enumerate()會更加直接和優(yōu)美:
list1 = ["這", "是", "一個", "測試"] for index, item in enumerate(list1): print index, item >>> 0 這 1 是 2 一個 3 測試
enumerate還可以接收第二個參數(shù),用于指定索引起始值,如:
list1 = ["這", "是", "一個", "測試"] for index, item in enumerate(list1, 1): print index, item >>> 1 這 2 是 3 一個 4 測試
補(bǔ)充
如果要統(tǒng)計(jì)文件的行數(shù),可以這樣寫:
count = len(open(filepath, 'r').readlines())
這種方法簡單,但是可能比較慢,當(dāng)文件比較大時甚至不能工作。
可以利用enumerate():
count = 0 for index, line in enumerate(open(filepath,'r')): count += 1
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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