... The sequence never stops. Example: 1 2 -1 2 -3 -1 34 12 ...................... it never stops. But I have to stop reading if I encounter -1.
raw_input()始终读取整行。在
如果您不想阅读整行内容,可以改为尝试sys.stdin.read(1):import sys
def read_until_minus_one():
buf = []
seen_minus = False
while True:
char = sys.stdin.read(1)
if not char: # EOF
break
if char == '1' and seen_minus:
buf.pop() # chop the last minus
break # seen -1
else:
seen_minus = (char == '-')
buf.append(char)
return ''.join(buf)
print(read_until_minus_one())
输出12 22 -23 13
注意:只要-1被读取,它就会停止。在本例中,后续的sys.stdin.read(1)返回{}。在
如果您只想在-1作为空格分隔标记(而不是-12中作为数字的一部分)时停止,则输入解析可以分为两个阶段:将输入拆分为空格分隔的标记
获取令牌,直到遇到-1#!/usr/bin/env