[英]Assignment: Python 3.3: Using while loop to check for condition of attribute in class
[英]Assignment Condition in Python While Loop
在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'):
启动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
i
的while
主体 就个人而言,我喜欢使用break
和Mark的答案,但你也可以这样做:
a = None
def set_a(x):
global a
a = x
return a
while set_a(sys.stdin.read(1)) != '\n':
print('yo')
虽然我不推荐它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.