Python Enumerate Usage Summary __python

Source: Internet
Author: User
Tags python enumerate
Enumerate () description Enumerate () is a Python built-in function enumerate the dictionary is enumerated, enumerated meaning for an iterative (iterable)/Ergodic object (such as lists, strings), enumerate it into an index sequence, It allows both index and value enumerate to be used for counting in the For loop

For example, for a seq, get:

(0, Seq[0]), (1, seq[1]), (2, seq[2])
      
      
       
       1
      
      
Enumerate () Returns a enumerate object, for example:
enumerate () using If you have a list that traverses both the index and the elements, you can first write this:
List1 = ["This", "yes", "one", "test"] for
I in range (len (list1)):
    print I, List1[i]
    
    
     
     1
     
     2
     
     3
    
    
The above method is somewhat cumbersome, using enumerate () will be more direct and graceful:
List1 = ["This", "yes", "one", "test"] for
index, item in enumerate (LIST1):
    print Index, item
>>>
0 This 
   1 is
21
3 Test
    
    
     
     1
     
     2
     
     3
     
     4 5 6 7 8
    
    
Enumerate can also receive a second parameter that specifies the starting value of the index, such as:
List1 = ["This", "yes", "one", "test"] for
index, item in enumerate (List1, 1):
    print Index, item
>>>
1
of this 2 is
31
4 test
    
    
     
     1
     
     2 3 4 5 6 7 8
    
    
Supplements

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

count = Len (open (filepath, ' R '). ReadLines ()) 1 

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

Can take advantage of enumerate ():

count = 0 for index, line in enumerate (open (filepath, ' R ')): Coun t = 1 1 2 3 

Reprint: http://blog.csdn.net/churximi/artic le/details/51648388

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.