简体   繁体   中英

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:

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. So for instance (the ^D is me typing CTRL+D at the console from a pycharm debugger):

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.

Thanks to @chepner and to this other thread I reduced this whole logic to:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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