Home  >  Article  >  Backend Development  >  Introduction to the usage of python function enumerate

Introduction to the usage of python function enumerate

巴扎黑
巴扎黑Original
2017-08-17 10:38:072344browse

The enumerate function is used to traverse the elements in the sequence and their subscripts.

enumerate function description:

Function prototype: enumerate(sequence, [start=0])

Function: List the sequence data separately starting the loopable sequence sequence with start and data subscript

That is, for a traversable data object (such as a list, tuple, or string), enumerate will combine the data object into an index sequence and list the data and data subscript at the same time.

Example:

There is a sequence, and using enumerate on it will get the following results:

start sequence[0]

start+1 sequence [1]

start+2 sequence[2]......

Applicable version:

Python2.3+

Python2.x

Note: The start parameter has been added after python2.6

English explanation:

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.

Code example:

The enumerate parameters are traversable variables, such as strings, lists, etc.; the return value is the enumerate class.

import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)

The output is:

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 you need both index and value values.

In this example, line is a string containing 0 and 1. Find all 1s:

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 usage of python function enumerate. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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