Example parsing of enumerate usage in python, pythonenumerate

Source: Internet
Author: User

Example parsing of enumerate usage in python, pythonenumerate

In python, the usage of enumerate is mostly used to get the count in the 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.


** Prefix usage in python. Here is an example (with points)

Def fun (p, ** args ):
Print args

Fun (1, a = 2, B = 3, c = 4, d = 5)

How to Use the iterator in python? For example,

Are you talking about enumerate?

The simplest example is as follows:
ListValue = ["a", "B", "c"]
For index, strValue in enumerate (listValue ):
Print index, "is", strValue

The result is:
0 is
1 is B
2 is c
 

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.