python遍歷序列enumerate函數(shù)淺析
enumerate函數(shù)用于遍歷序列中的元素以及它們的下標。
enumerate函數(shù)說明:
函數(shù)原型:enumerate(sequence, [start=0])
功能:將可循環(huán)序列sequence以start開始分別列出序列數(shù)據(jù)和數(shù)據(jù)下標
即對一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串),enumerate會將該數(shù)據(jù)對象組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標。
舉例說明:
存在一個sequence,對其使用enumerate將會得到如下結果:
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)
輸出為:
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函數(shù)淺析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Python enumerate函數(shù)遍歷數(shù)據(jù)對象組合過程解析
- Python range、enumerate和zip函數(shù)用法詳解
- python中enumerate() 與zip()函數(shù)的使用比較實例分析
- Python學習筆記之Zip和Enumerate用法實例分析
- Python enumerate函數(shù)功能與用法示例
- Python中enumerate()函數(shù)編寫更Pythonic的循環(huán)
- Python enumerate索引迭代代碼解析
- python enumerate函數(shù)的使用方法總結
- Python中enumerate函數(shù)代碼解析
- Python使用enumerate獲取迭代元素下標
相關文章
python實現(xiàn)0到1之間的隨機數(shù)方式
這篇文章主要介紹了python實現(xiàn)0到1之間的隨機數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07淺談numpy中函數(shù)resize與reshape,ravel與flatten的區(qū)別
這篇文章主要介紹了淺談numpy中函數(shù)resize與reshape,ravel與flatten的區(qū)別介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python實現(xiàn)去除列表中重復元素的方法小結【4種方法】
這篇文章主要介紹了Python實現(xiàn)去除列表中重復元素的方法,結合實例形式總結分析了Python列表去重的4種實現(xiàn)方法,涉及Python針對列表的遍歷、判斷、排序等相關操作技巧,需要的朋友可以參考下2018-04-04