Python enumerate usage, pythonenumerate

Source: Internet
Author: User

Python enumerate usage, pythonenumerate

A new built-in function,Enumerate (), Will make certain loops a bit clearer.enumerate(thing), WhereThingIs either an iterator or a sequence, returns a iterator that will return(0, thing [0]),(1, thing [1]),(2, thing [2]), And so forth.

A common idiom to change every element of a list looks like this:

Usage: it can be used when both index and value are required.

Line = [1, 3, 'dfd ', 'jdjfjd'] for I in range (len (line): item = line [I] print (I, "---> ", item) # running result: 0 ---> 11 ---> 32 ---> dfd3 ---> jdjfjd

It is equivalent to the following code:

line = [1,3,'dfd','jdjfjd']for i,item in enumerate(line):    print(i,"-------",item)

 

Enumerate practice

Line is a string containing 0 and 1. We need to find out 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 ('123') print list (xread_line ('123 '))

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.