Python循环时的赋值条件

tek*_*agi 28 python loops while-loop conditional-statements

在C中,人们可以做到

while( (i=a) != b ) { }
Run Code Online (Sandbox Code Playgroud)

但在Python中,它似乎不可能.

while (i = sys.stdin.read(1)) != "\n":
Run Code Online (Sandbox Code Playgroud)

生成

    while (i = sys.stdin.read(1)) != "\n":
         ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

( ^应该在=)

有解决方法吗?

Mar*_*ers 22

使用休息:

while True:
    i = sys.stdin.read(1)
    if i == "\n":
       break
    # etc...
Run Code Online (Sandbox Code Playgroud)

  • @FalconMomot这对我来说似乎是一个非常合理的模式.循环被破坏的重要性是什么?终止条件将发生,或者不会发生.如果`i =="\n"`在循环内部没有发生(导致中断),那么在while循环的条件参数中也不会发生这种情况. (3认同)

And*_*ark 9

您可以使用内置函数iter()使用双参数调用方法完成此操作:

import functools
for i in iter(fuctools.partial(sys.stdin.read, 1), '\n'):
    ...
Run Code Online (Sandbox Code Playgroud)

这方面的文件:

iter(o[, sentinel])
...
如果给出第二个参数sentinel,则o必须是可调用对象.在这种情况下创建的迭代器将为每个对其方法的调用调用o而不带参数next(); 如果返回的值等于sentinel,StopIteration则会引发,否则返回值.

第二种形式的一个有用的应用iter()是读取文件的行直到达到某一行.以下示例读取文件,直到该readline()方法返回空字符串:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)
Run Code Online (Sandbox Code Playgroud)


Arm*_*ali 7

没有的版本functools:

for i in iter(lambda: sys.stdin.read(1), '\n'):
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 5

从开始Python 3.8并引入赋值表达式(PEP 572):=运算符)以来,现在可以将表达式值(此处sys.stdin.read(1))捕获为变量,以便在以下主体中使用它while

while (i := sys.stdin.read(1)) != '\n':
  do_smthg(i)
Run Code Online (Sandbox Code Playgroud)

这个:

  • 分配sys.stdin.read(1)给变量i
  • 相比i\n
  • 如果条件得到验证,请输入可以使用的while正文i