简体   繁体   English

使用生成器在多行上整理用户输入

[英]Using generator to collate user inputs on multiple lines

I am trying to save some memory here - I am building a program where the user can input a (stacked) list of integers like:我正在尝试在这里保存一些 memory - 我正在构建一个程序,用户可以在其中输入(堆叠)整数列表,例如:

1
2
3
4
5
.
.
.

The below code works good!下面的代码效果很好!

input_list = []

while True:
    try:
        line = input()
    except EOFError:
        break
    input_list.append(int(line))

print(input_list)

But I would now like to use some sort of generator expression to evaluate the list only when I need, and I almost (argh.) got there.我现在想只在需要时使用某种生成器表达式来评估列表,而且我几乎(啊)到了那里。

This code works:此代码有效:

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))

with one only quack: the last integer input by the user is always omitted.只有一个庸医:用户输入的最后一个 integer 总是被省略。 So for instance (the ^D is me typing CTRL+D at the console from a pycharm debugger):例如( ^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]

I don't really know how to go further.我真的不知道如何进一步 go 。

Thanks to @chepner and to this other thread I reduced this whole logic to:感谢@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))

leveraging the fact that sys.stdin is already iterable!利用sys.stdin已经是可迭代的事实!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM