Assign variable in while loop condition in Python?

前端 未结 11 1497
名媛妹妹
名媛妹妹 2020-12-08 03:39

I just came across this piece of code

while 1:
    line = data.readline()
    if not line:
        break
    #...

and thought, there must

相关标签:
11条回答
  • 2020-12-08 04:30
    for line in data:
        ... process line somehow....
    

    Will iterate over each line in the file, rather than using a while. It is a much more common idiom for the task of reading a file in my experience (in Python).

    In fact, data does not have to be a file but merely provide an iterator.

    0 讨论(0)
  • 2020-12-08 04:34

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (data.readline()) of the while loop as a variable (line) in order to re-use it within the body of the loop:

    while line := data.readline():
      do_smthg(line)
    
    0 讨论(0)
  • 2020-12-08 04:34

    If data is a file, as stated in other answers, using for line in file will work fine. If data is not a file, and a random data reading object, then you should implement it as an iterator, implementing __iter__ and next methods.

    The next method should to the reading, check if there is more data, and if not, raise StopIteration. If you do this, you can continue using the for line in data idiom.

    0 讨论(0)
  • 2020-12-08 04:35

    If you aren't doing anything fancier with data, like reading more lines later on, there's always:

    for line in data:
        ... do stuff ...
    
    0 讨论(0)
  • 2020-12-08 04:36

    If data has a function that returns an iterator instead of readline (say data.iterate), you could simply do:

    for line in data.iterate():
        #...
    
    0 讨论(0)
提交回复
热议问题