【发布时间】:2011-06-21 14:41:38
【问题描述】:
在C编程语言中,我经常做以下事情:
while ((c = getch()) != EOF) {
/* do something with c */
}
在 Python 中,我没有发现任何类似的东西,因为我不允许在计算表达式中设置变量。我通常最终不得不设置两次评估表达式!
c = sys.stdin.read(1)
while not (c == EOF):
# Do something with c
c = sys.stdin.read(1)
在我尝试找到更好的方法时,我发现了一种只需要设置和评估一次表达式的方法,但这越来越难看...
while True:
c = sys.stdin.read(1)
if (c == EOF): break
# do stuff with c
到目前为止,对于某些情况,我已经解决了以下方法,但这对于常规的 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
我解决一个简单的基本编程问题的所有解决方案都变得太复杂了...... 有没有人建议如何以正确的方式做到这一点?
【问题讨论】:
-
我发现了这个:python.org/dev/peps/pep-0315 但遗憾的是,它还没有实现......
-
非常类似于这个问题:stackoverflow.com/questions/2941272/…
-
您可能对我对do…while vs while 的回答感兴趣——有点切题,但仍然相关。