在C中,人们可以做到
while( (i=a) != b ) { }
但是在Python中,它似乎不可能。
while (i = sys.stdin.read(1)) != "\n":
生成
while (i = sys.stdin.read(1)) != "\n":
^
SyntaxError: invalid syntax
(^
应该在=
上)
有解决方法吗?
使用休息:
while True:
i = sys.stdin.read(1)
if i == "\n":
break
# etc...
您可以使用内置函数iter()
使用双参数调用方法完成此操作:
import functools
for i in iter(fuctools.partial(sys.stdin.read, 1), '\n'):
...
这方面的文件:
iter(o[, sentinel])
... 如果给出第二个参数sentinel,则o必须是可调用对象。在这种情况下创建的迭代器将为每次调用next()
方法调用o而不带参数;如果返回的值等于sentinel,则会引发StopIteration
,否则返回该值。第二种形式的
iter()
的一个有用的应用是读取文件的行直到达到某一行。以下示例读取文件,直到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'):
我个人喜欢使用break
的imm和Marks答案,但你也可以这样做:
a = None
def set_a(x):
global a
a = x
return a
while set_a(sys.stdin.read(1)) != '\n':
print('yo')
虽然我不推荐它。
启动Python 3.8
,并引入assignment expressions (PEP 572)(:=
运算符),现在可以将表达式值(此处为sys.stdin.read(1)
)捕获为变量,以便在while
体内使用它:
while (i := sys.stdin.read(1)) != '\n':
do_smthg(i)
这个:
sys.stdin.read(1)
分配给变量i
i
和\n
while
的i
体