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

问题描述 投票:0回答:1

我想在这里节省一些内存--我正在建立一个程序,在这个程序中,用户可以输入一个(堆叠的)整数列表,比如。

1
2
3
4
5
.
.
.

下面的代码很好用!

input_list = []

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

print(input_list)

但是 我现在想使用某种生成器表达式,只在我需要的时候才对列表进行评估,而且我 几乎 (argh!)到了。

这段代码可以用。

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

只有一个问题: 用户输入的最后一个整数总是被省略. 因此,例如(用户输入的 ^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]

我真的不知道该如何继续下去。

python memory input generator eof
1个回答
0
投票

感谢 @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 已经可以迭代了!

© www.soinside.com 2019 - 2024. All rights reserved.