Usage instance parsing of enumerate in Python

Source: Internet
Author: User
The usage of enumerate in Python is used to get counted in the For loop, and this article shows you the use of enumerate in Python as an instance. Specific as follows:

The enumerate parameter is a variable that can be traversed, such as a string, a list, and so on; The return value is the enumerate class.

The sample code looks like this:

Import strings = String.ascii_lowercasee = Enumerate (s) Print sprint 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 both the index and value values are required.

Enumerate Application Examples:

In this example, line is a string containing 0 and 1, to find out the 1:

Method One:

def read_line:  sample = {}  n = len (line) for I in  range (n):    if line[i]!= ' 0 ':      sample[i] = Int (li Ne[i])  return sample

Method Two:

def xread_line (line):  return ((Idx,int (val)) for IDX, Val-Enumerate (line) if val! = ' 0 ') print read_line (' 0001110101 ') Print List (Xread_line (' 0001110101 '))

I believe this example will help you deepen the usage of enumerate in Python.

  • 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.