Home >Backend Development >Python Tutorial >A simple way to get the list subscript and its value in python

A simple way to get the list subscript and its value in python

高洛峰
高洛峰Original
2017-02-23 11:29:253496browse

When traversing a sequence in python, we usually use the following method:

for item in sequence:
    process(item)

If you want to get the position of a certain item , you can write like this:

for index in range(len(sequence)):
    process(sequence[index])

Another better way is to use python’s built-in enumerate function:

enumerate(sequence,start=0)

In the above function, sequence is an iterable object, which can be a list, dictionary, file object, etc. enumerate returns a tuple consisting of subscript and item:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

The first example of the article can be written like this:

for index,item in enumerate(sequence):
    print index,item

The above simple method of obtaining the list subscript and its value in Python is all the content shared by the editor. I hope it can give you a reference. I also hope that everyone will support the PHP Chinese website.

For more related articles on the simple method of obtaining list subscripts and their values ​​in python, please pay attention to 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