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

高洛峰
Release: 2017-02-23 11:29:25
Original
3408 people have browsed it

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

for item in sequence:
    process(item)
Copy after login

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])
Copy after login

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

enumerate(sequence,start=0)
Copy after login

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')]
Copy after login

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

for index,item in enumerate(sequence):
    print index,item
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!