The first 2 methods are mainly used in list parsing, performance is slightly poor, and the last use of the generator expression, compared to list parsing, more memory-saving
List resolution and builder expressions are similar:
List resolution
[Expr for Iter_var in iterable if COND_EXPR]
Builder expression
(Expr for Iter_var in iterable if cond_expr)
Method 1: The original
Copy Code code 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
Method 2: Concise
Copy Code code as follows:
f = open (File_path, "R")
Alllinelens = [Len (Line.strip ()) for line in F]
Longest = max (Alllinelens)
F.close ()
Disadvantage: When iterating over a line of F, list resolution needs to read all the rows of the file into memory, and then generate the list
Method 3: The most concise, most memory saving
Copy Code code as follows:
f = open (File_path, "R")
Longest = max (Len (line) to line in F)
F.close ()
Or
Copy Code code as follows:
Print Max (len (Line.strip ()) for line in Open (File_path))