[英]How to read input from the command line's standard input in Python?
我想用空行分隔输入,重复读取输入,直到收到 2 个空行。 这是预期的输入格式:
A
B
C
A B 2
A C 3
C B 4
A B 1
我努力了
for line in sys.stdin:
node = [line]
if line == ' ':
cost = [line.split()]
if line == ' ':
distance = [line.split()]
但它不能停止读取带有 2 个空行的输入。 有什么建议吗?
这是一个非常简单的循环,可以存储您lines
中提供的任何输入
当最后两行为空时,即lines[-1]==lines[-2]==""
然后 break; [只需确保您已从用户那里获取至少 2 个输入,因此请检查len(lines)>2
]
lines = []
while True:
inp = input()
lines.append(inp.strip())
if len(lines)>2 and lines[-1]==lines[-2]=="":
break
print('\n'.join(lines))
A
B
C
A B 2
A C 3
C B 4
A B 1
如果您不想存储所有行
lines = ['temp', 'temp']
while True:
inp = input()
lines[-2], lines[-1] = lines[-1], inp.strip() # this changes the second last element by last one and the last one is updated to the new line that is entered
if lines[-1]==lines[-2]=="":
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.