Home > Backend Development > Python Tutorial > Introduction to the practical usage of python learning enumerate

Introduction to the practical usage of python learning enumerate

高洛峰
Release: 2017-03-20 13:02:04
Original
1634 people have browsed it

A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , whereis either an iterator or a sequence, returns an iterator that will return (0,[0]) , (1,[1]) , (2,[2]) , and so forth.

A common idiom to change every element of a list looks like this:

Usage: Can be used when both index and value are needed

line = [1,3,'dfd','jdjfjd']
for i in range(len(line)):
    item = line[i]
    print(i,"--->",item)

#运行结果:
---> 1
---> 3
---> dfd
---> jdjfjd
Copy after login

is equivalent to the following code:

line = [1,3,'dfd','jdjfjd']
for i,item in enumerate(line):
    print(i,"-------",item)
Copy after login

enumerate Actual

line is a string containing 0 and 1, you need to find all 1:

#Method 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

#Method 2

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'))


The above is the detailed content of Introduction to the practical usage of python learning enumerate. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template