在C编程语言中,我经常做以下事情:
while ((c = getch()) != EOF) {
/* do something with c */
}
Run Code Online (Sandbox Code Playgroud)
在Python中,我没有发现任何类似的东西,因为我不允许在evaluate表达式中设置变量.我通常最终必须设置两次评估表达式!
c = sys.stdin.read(1)
while not (c == EOF):
# Do something with c
c = sys.stdin.read(1)
Run Code Online (Sandbox Code Playgroud)
在我试图找到更好的方法时,我找到了一种只需要设置和评估表达式一次的方法,但这变得更加丑陋......
while True:
c = sys.stdin.read(1)
if (c == EOF): break
# do stuff with c
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经针对我的一些情况采用了以下方法,但这对于常规while循环来说远非最佳...:
class ConditionalFileObjectReader:
def __init__(self,fobj, filterfunc):
self.filterfunc = filterfunc
self.fobj = fobj
def __iter__(self):
return self
def next(self):
c = self.fobj.read(1)
if self.filterfunc(c): raise StopIteration
return c
for c in ConditionalFileObjectReader(sys.stdin,lambda c: c == EOF):
print c
Run Code Online (Sandbox Code Playgroud)
解决一个简单的基本编程问题的所有解决方案都变得过于复杂......有没有人建议如何以正确的方式做到这一点?
Sve*_*ach 18
你通常会for在Python中使用一个循环:
for c in sys.stdin.read():
# whatever
Run Code Online (Sandbox Code Playgroud)
如果您不想一次在内存中缓冲整个stdin,您也可以自己添加一些缓冲区和缓冲区.
请注意,EOFPython中不存在常量. read()如果流中没有数据,则只返回一个空字符串.
Pon*_*dle 13
我相信你想要做的就是利用这个iter功能.
for c in iter(getch, EOF):
#inner loop
Run Code Online (Sandbox Code Playgroud)
Iter是一个非常通用的功能.在这种情况下,你告诉它getch在每个循环的顶部重复调用(没有参数),直到getch返回sentinel值EOF.