[英]Using generator to collate user inputs on multiple lines
我正在尝试在这里保存一些 memory - 我正在构建一个程序,用户可以在其中输入(堆叠)整数列表,例如:
1
2
3
4
5
.
.
.
下面的代码效果很好!
input_list = []
while True:
try:
line = input()
except EOFError:
break
input_list.append(int(line))
print(input_list)
但我现在想只在需要时使用某种生成器表达式来评估列表,而且我几乎(啊)到了那里。
此代码有效:
def prompt_user():
while True:
try:
line = input()
except EOFError:
print(line)
break
yield line
input_list = (int(line) for line in prompt_user())
print(list(input_list))
只有一个庸医:用户输入的最后一个 integer 总是被省略。 例如( ^D
是我从 pycharm 调试器在控制台上键入 CTRL+D):
1
2
3
4^D
3 # ==> seems like after the EOF was detected the integer on the same
# line got completely discarded
[1, 2, 3]
我真的不知道如何进一步 go 。
感谢@chepner 和另一个线程,我将整个逻辑简化为:
import sys
N = input() # input returns the first element in our stacked input.
input_list = map(int, [N] + sys.stdin.readlines())
print(list(input_list))
利用sys.stdin
已经是可迭代的事实!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.