python中enumerate的用法實例解析
更新時間:2014年08月18日 16:20:47 投稿:shichen2014
這篇文章主要介紹了python中enumerate的用法,對Python初學者而言是非常重要的概念,需要的朋友可以參考下
在python中enumerate的用法多用于在for循環(huán)中得到計數,本文即以實例形式向大家展現python中enumerate的用法。具體如下:
enumerate參數為可遍歷的變量,如 字符串,列表等; 返回值為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。
enumerate應用實例:
該實例中,line 是個 string 包含 0 和 1,要把1都找出來:
方法一:
def read_line(line): sample = {} n = len(line) for i in range(n): if line[i]!='0': sample[i] = int(line[i]) return sample
方法二:
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的用法能夠起到一定的幫助作用。
相關文章
python爬蟲開發(fā)之Request模塊從安裝到詳細使用方法與實例全解
這篇文章主要介紹了python爬蟲開發(fā)之Request模塊從安裝到詳細使用方法與實例全解,需要的朋友可以參考下2020-03-03Python.append()與Python.expand()用法詳解
今天小編就為大家分享一篇Python.append()與Python.expand()用法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12