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)
您可以使用内置函数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)
没有的版本functools:
for i in iter(lambda: sys.stdin.read(1), '\n'):
Run Code Online (Sandbox Code Playgroud)
从开始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)给变量ii于\nwhile正文i