Assign variable in while loop condition in Python?

前端 未结 11 1496
名媛妹妹
名媛妹妹 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:13

    You could do:

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

    According to the FAQ from Python's documentation, iterating over the input with for construct or running an infinite while True loop and using break statement to terminate it, are preferred and idiomatic ways of iteration.

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

    Like,

    for line in data:
        # ...
    

    ? It large depends on the semantics of the data object's readline semantics. If data is a file object, that'll work.

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

    As of python 3.8 (which implements PEP-572) this code is now valid:

    while line := data.readline():
       # do something with line 
    
    0 讨论(0)
  • 2020-12-08 04:26

    This isn't much better, but this is the way I usually do it. Python doesn't return the value upon variable assignment like other languages (e.g., Java).

    line = data.readline()
    while line:
        # ... do stuff ... 
        line = data.readline()
    
    0 讨论(0)
  • 2020-12-08 04:28

    Try this one, works for files opened with open('filename')

    for line in iter(data.readline, b''):
    
    0 讨论(0)
提交回复
热议问题