简体   繁体   中英

Syntax: Compacted For Loop in python

What is going on here?

with open('contractors.txt','r') as in_file:  
    stripped = (line.strip() for line in in_file)   
    lines = (line for line in stripped if line)

Is this a syntactic equivalent to:

for line in in_file:
    stripped = line.strip()
for line in stripped:
    lines =  line

The "compacted for loops" are called generator expressions , which are more-or-less equivalent to list comprehensions that return generators instead of lists.

In the code you're looking at, the stripped generator expression str.strip() s each line of the opened file, and the lines generator expression drops any blank lines from stripped . The end result is a generator ( lines ) that, when iterated over, will generate the stripped version of the non-empty lines of the file.

It's important to note that since you're just working with generators, after these lines are run nothing has actually been read from the file yet . If you end the with block, the file will be closed and attempting to pull anything from lines will result in an I/O error. So anything you want to do with it has to be done within that block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM