This article mainly introduces the usage of enumerate in python, which is a very important concept for beginners of Python, for more information about how to use enumerate in python, you can use enumerate in a for loop. This article shows you how to use enumerate in python in the form of an instance. The details are as follows:
The enumerate parameter is a variable that can be traversed, such as a string or a list. The returned value is the enumerate class.
The sample code is as follows:
import strings = string.ascii_lowercasee = enumerate(s)print sprint list(e)
Output:
abcdefghij[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
You can use enumerate when both the index and value values are required.
Enumerate application instance:
In this instance, line is a string that contains 0 and 1. We 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'))
I believe this example will help you to deepen the usage of enumerate in Python.