[英]Assignment Condition in Python While Loop
In C, one can do 在C中,人们可以做到
while( (i=a) != b ) { }
but in Python, it appears, one cannot. 但是在Python中,它似乎不可能。
while (i = sys.stdin.read(1)) != "\n":
generates 生成
while (i = sys.stdin.read(1)) != "\n":
^
SyntaxError: invalid syntax
(the ^
should be on the =
) (
^
应该在=
)
Is there a workaround? 有解决方法吗?
Use break: 使用休息:
while True:
i = sys.stdin.read(1)
if i == "\n":
break
# etc...
You can accomplish this using the built-in function iter()
using the two-argument call method: 您可以使用内置函数
iter()
使用双参数调用方法来完成此操作:
import functools
for i in iter(fuctools.partial(sys.stdin.read, 1), '\n'):
...
Documentation for this: 这方面的文件:
iter(o[, sentinel])
......
If the second argument, sentinel , is given, then o must be a callable object.如果给出第二个参数sentinel ,则o必须是可调用对象。 The iterator created in this case will call o with no arguments for each call to its
next()
method;在这种情况下创建的迭代器将为每个对
next()
方法的调用调用o而不带参数; if the value returned is equal to sentinel ,StopIteration
will be raised, otherwise the value will be returned.如果返回的值等于sentinel ,则会引发
StopIteration
,否则返回该值。One useful application of the second form of
iter()
is to read lines of a file until a certain line is reached.第二种形式的
iter()
一个有用的应用是读取文件的行直到达到某一行。 The following example reads a file until thereadline()
method returns an empty string:以下示例读取文件,直到
readline()
方法返回空字符串:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
没有functools
的版本:
for i in iter(lambda: sys.stdin.read(1), '\n'):
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) ( :=
operator), it's now possible to capture an expression value (here sys.stdin.read(1)
) as a variable in order to use it within the body of while
: 启动
Python 3.8
,并引入赋值表达式(PEP 572) ( :=
运算符),现在可以捕获表达式值(此处为sys.stdin.read(1)
)作为变量,以便在正文中使用它while
:
while (i := sys.stdin.read(1)) != '\n':
do_smthg(i)
This: 这个:
sys.stdin.read(1)
to a variable i
sys.stdin.read(1)
分配给变量i
i
to \\n
i
到\\n
while
body in which i
can be used i
的while
主体 Personally I like imm's and Marks answers using break
, but you could also do: 就个人而言,我喜欢使用
break
和Mark的答案,但你也可以这样做:
a = None
def set_a(x):
global a
a = x
return a
while set_a(sys.stdin.read(1)) != '\n':
print('yo')
though I wouldn't recommend it. 虽然我不推荐它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.