C语言中,可以进行以下操作:
while( (i=a) != b ) { }
但在Python中似乎是不行的。
while (i = sys.stdin.read(1)) != "\n":
生成
while (i = sys.stdin.read(1)) != "\n":
^
SyntaxError: invalid syntax
(^
应该在 =
上方)
有什么解决方法吗?
C语言中,可以进行以下操作:
while( (i=a) != b ) { }
但在Python中似乎是不行的。
while (i = sys.stdin.read(1)) != "\n":
生成
while (i = sys.stdin.read(1)) != "\n":
^
SyntaxError: invalid syntax
(^
应该在 =
上方)
有什么解决方法吗?
从 Python 3.8
开始,并引入了 赋值表达式(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
使用 break 关键字:
while True:
i = sys.stdin.read(1)
if i == "\n":
break
# etc...
i == "\n"
没有在循环内发生(导致退出循环),它也不会在 while 循环的条件中发生。 - vastlysuperiormaniter()
并进行双参数调用来完成此操作: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'):
我个人喜欢imm和Mark的答案,他们使用了break
,但你也可以这样做:
a = None
def set_a(x):
global a
a = x
return a
while set_a(sys.stdin.read(1)) != '\n':
print('yo')
readline()
和raw_input()
有什么区别? - tekknolagiwhile True
来替代。 - Trevor Robinson