A simple method for python to obtain list subscript and its value

Source: Internet
Author: User
The following is a simple method for python to obtain the list subscript and its values. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the following method when traversing a sequence in python:

for item in sequence:    process(item)

If you want to get the position of an item, you can write as follows:

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

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

enumerate(sequence,start=0)

In the above functions, sequence is an iteratable object, which can be a list, dictionary, and file object. Enumerate returns a triple 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 example at the beginning of the article can be written as follows:

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

The simple way to obtain the list subscript and its value in the above python article is to share all the content with you. I hope to give you a reference and support for PHP.

For more articles about how to obtain the list subscript and its value in python, refer to PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.