Python Advanced application Case comparison: Efficiently compute the length of the longest line in a large file _python

Source: Internet
Author: User
Tags iterable

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

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.