在 Python 中分配 while 循环条件中的变量?

我刚刚发现了这段代码

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

并且认为,与使用 break的无限循环相比,必须的有更好的方法来做到这一点。

所以我试着:

while line = data.readline():
#...

很明显,出错了。

在这种情况下有什么办法可以避免使用 break吗?

编辑:

理想情况下,您应该避免说 readline两次... ... 恕我直言,重复甚至比仅仅说 break更糟糕,特别是如果语句是复杂的。

93753 次浏览

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

You could do:

line = 1
while line:
line = data.readline()
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.

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.

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

for line in data:
... do stuff ...

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

for line in data.iterate():
#...

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.

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

for line in iter(data.readline, b''):

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.

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)

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

while line := data.readline():
# do something with line