Python advanced application: quickly and effectively calculates the maximum length of rows in a large file

Source: Internet
Author: User

Advanced Python application: quick and effective calculation of the maximum length of rows in a large file. The first two methods mainly use list parsing, with poor performance. The last method is a generator expression, compared with list parsing, it saves more memory and improves a lot of efficiency. You can try it.

List Parsing is similar to generator expressions:

List Parsing

[Expr for iter_var in iterable if cond_expr]

Generator expression

(Expr for iter_var in iterable if cond_expr)

Python advanced application: fast and effective calculation of the longest row length in a large file Method 1: the most primitive

 

Copy codeThe Code is as follows:
Longest = 0
F = open (FILE_PATH, "r ")
AllLines = [line. strip () for line in f. readlines ()]
F. close ()
For line in allLines:
Linelen = len (line)
If linelen> longest:
Longest = linelen

 

Python advanced application: fast and effective method for calculating the longest line length in a large file 2: Concise

 

Copy codeThe Code is as follows:
F = open (FILE_PATH, "r ")
AllLineLens = [len (line. strip () for line in f]
Longest = max (allLineLens)
F. close ()

 

Disadvantage: when one row iterates f, the list parsing needs to read all the lines of the file into the memory, and then generate a list

Advanced Python applications: fast and effective calculation of the longest row length in a large file method 3: The most concise, the most memory-saving

 

Copy codeThe Code is as follows:
F = open (FILE_PATH, "r ")
Longest = max (len (line) for line in f)
F. close ()

 

Or

 

Copy codeThe Code is as follows:
Print max (len (line. strip () for line in open (FILE_PATH ))

 

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.