python enumerate 用法


python enumerate 用法 [Python俱樂部]

python enumerate 用法

python enumerate 用法 | 在for循環中得到計數

參數為可遍歷的變量,如 字符串,列表等;
返回值為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'))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM