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 ))