Python daily improvement (7)-enumerate usage

Source: Internet
Author: User

Python cookbook Recipe 2.5. Counting Lines in a File,

A new function enumerate was found today. In general, if you want to traverse both the index and element of a list or array, write as follows:

For I in range (0, len (list )):
Print I, list [I], but this method is somewhat cumbersome. Using the built-in enumerrate function is more straightforward and elegant. Let's first look at the definition of enumerate:

Def enumerate (collection ):
'Generates an indexed series: (0, coll [0]), (1, coll [1])...'
I = 0
It = iter (collection)
While 1:
Yield (I, it. next ())
I + = 1


Enumerate combines an array or list into an index sequence. This makes it easier to obtain the index and index content as follows:

For index, text in enumerate (list )):
Print index, text


In cookbook, if you want to calculate the number of lines in the file, you can write it as follows:

Count = len (open (thefilepath, 'ru '). readlines ())

The preceding method is simple, but may be slow. When the file is large or cannot work, the following method is more suitable for reading cyclically.

Count =-1
For count, line in enumerate (open (thefilepath, 'ru ')):
Pass
Count + = 1

Vivilisa write in 03.19.2009

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.