Instance parsing of enumerate usage in python

Source: Internet
Author: User
This article mainly introduces the usage of enumerate in python, which is a very important concept for beginners of Python, for more information about how to use enumerate in python, you can use enumerate in a for loop. This article shows you how to use enumerate in python in the form of an instance. The details are as follows:

The enumerate parameter is a variable that can be traversed, such as a string or a list. The returned value is the enumerate class.

The sample code is as follows:

import strings = string.ascii_lowercasee = enumerate(s)print sprint list(e)

Output:

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

In this instance, line is a string that contains 0 and 1. We need to find all 1:

Method 1:

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

Method 2:

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'))

I believe this example will help you to 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.