简体   繁体   English

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

[英]Assign variable in while loop condition in Python?

I just came across this piece of code我刚刚遇到了这段代码

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

and thought, there must be a better way to do this, than using an infinite loop with break .并认为,必须有更好的方法来做到这一点,而不是使用带有break的无限循环。

So I tried:所以我尝试了:

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

and, obviously, got an error.而且,显然,有一个错误。

Is there any way to avoid using a break in that situation?有没有办法避免在这种情况下使用break

Edit:编辑:

Ideally, you'd want to avoid saying readline twice... IMHO, repeating is even worse than just a break , especially if the statement is complex.理想情况下,您应该避免说readline两次...恕我直言,重复甚至比break更糟糕,尤其是在语句很复杂的情况下。

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:Python 3.8开始,并引入赋值表达式 (PEP 572) ( :=运算符),现在可以将 while 循环的条件值 ( data.readline() ) 捕获为变量 ( line ),以便重新在循环体内使用它:

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

Try this one, works for files opened with open('filename')试试这个,适用于用open('filename')

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

If you aren't doing anything fancier with data, like reading more lines later on, there's always:如果您没有对数据做任何更有趣的事情,例如稍后阅读更多行,那么总会有:

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

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 (eg, Java). Python 不会像其他语言(例如,Java)那样在变量赋值时返回值。

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

Like,喜欢,

for line in data:
    # ...

? ? It large depends on the semantics of the data object's readline semantics.它很大程度上取决于data对象的 readline 语义的语义。 If data is a file object, that'll work.如果data是一个file object,那就可以了。

As of python 3.8 (which implements PEP-572 ) this code is now valid:从 python 3.8 (实现PEP-572 )开始,此代码现在有效:

while line := data.readline():
   # do something with line 
for line in data:
    ... process line somehow....

Will iterate over each line in the file , rather than using a while .将遍历file中的每一行,而不是使用一段while It is a much more common idiom for the task of reading a file in my experience (in Python).根据我的经验(在 Python 中),读取文件的任务是一个更常见的习语。

In fact, data does not have to be a file but merely provide an iterator.实际上, data不必是文件,而只是提供一个迭代器。

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.根据 Python 文档中的常见问题解答,使用for构造迭代输入或运行无限while True循环并使用break语句终止它,是首选和惯用的迭代方式。

You could do:你可以这样做:

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

If data has a function that returns an iterator instead of readline (say data.iterate ), you could simply do:如果data有一个 function 返回一个迭代器而不是readline (比如data.iterate ),你可以简单地做:

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

If data is a file, as stated in other answers, using for line in file will work fine.如果data是一个文件,如其他答案中所述,使用for line in file可以正常工作。 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.如果 data 不是文件,并且是读取 object 的随机数据,那么您应该将其实现为迭代器,实现__iter__next方法。

The next method should to the reading, check if there is more data, and if not, raise StopIteration . next方法应该是读取,检查是否有更多数据,如果没有,则提高StopIteration If you do this, you can continue using the for line in data idiom.如果你这样做,你可以继续使用for line in data习惯用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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