Python enumrate use

Source: Internet
Author: User

New contact with a function enumrate, in many cases we want to get an iterative container (such as dict, list, tuple, etc.) elements, want to get a serial number for his use.

Code is often written like this.

List_a = ["Apple", "Dell", "HP", "IBM"]for idx in range (len (list_a)):    print ("Idx={0}, Content={1}". Format (IDX, list_ A[IDX]))

If it's dict, it'll be written like this.

Dict_a={"A": "Apple", "B": "Banana", "O": "orange"}IDX = 0for it in dict_a:    idx = idx + 1    print ("key[{0}]={1},idx={2 } ". Format (it, Dict_a[it], idx))

But the function has, beautiful poor

It's time for enumrate to play. The Enumrate function can return both the element and the index number. The above two examples can be written like this

List_a = ["Apple", "Dell", "HP", "IBM"]for Idx,val in Enumerate (list_a):    print ("Idx={0}, Content={1}". Format (IDX, val))

and the output is

Idx=0, Content=apple
Idx=1, Content=dell
idx=2, CONTENT=HP
Idx=3, CONTENT=IBM

And Dict can write like this.

For Idx,key in Enumerate (dict_a):    print ("key[{0}]={1},idx={2}". Format (KEY,DICT_A[KEY],IDX))

Output to

Key[b]=banana,idx=0
Key[o]=orange,idx=1
key[a]=apple,idx=2

In addition, learn how other bloggers use

If you want to count the number of lines in a file, you can write:

Count = Len (open (filepath, ' R '). ReadLines ())

This method is simple, but may be slow, and cannot even work when the file is larger.

You can use enumerate ():

Count = 0for index, line in enumerate (open (filepath, ' R ')):     count + = 1

  

Python enumrate use

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.