2

I have a programming assignment and all of the inputs that I need to enter are multilined. For example:

4 3
10 3
100 5
1000000000 8

or:

7 8 666
8 7 666
10 16 273

I am trying to convert the lines into lists. I can't use files and I need to be able to input them into the program using an input statement.

The problem I am having is, I want the output to be:

[['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']]

so I can use it to finish the rest of my program. But what I am getting is only:

[['4', '3']]

The code I have been trying to use is:

aString = input(" > ")
aString_list = [x for x in (y.split() for y in aString.split('\n')) if x]
print(aString_list)

I am confused on how to get it to read the other lines. Thanks.

2 Answers 2

2

The problem with your code is that input() stops as soon as you hit Enter, to get continuous input you need to use a either a while loop or a for loop and take input until user enters a sentinel value:

Using for-loop and iter:

def multiline_input(sentinel=''):
    for inp in iter(input, sentinel):
        yield inp.split()
...         
>>> lis = list(multiline_input())
1 2 3
400 500 600
a b c

>>> lis
[['1', '2', '3'], ['400', '500', '600'], ['a', 'b', 'c']]

Using while loop:

def multiline_input(sentinel=''):
    while True:
        inp = input()
        if inp != sentinel:
            yield inp.split()
        else:
            break
...             
>>> lis = list(multiline_input())
1 2
3 4 5
6 7 8 9
10

>>> lis
[['1', '2'], ['3', '4', '5'], ['6', '7', '8', '9'], ['10']]
Sign up to request clarification or add additional context in comments.

Comments

0

It may be something I do not understand, but in the performance of such code here

aString = """
4 3
10 3
100 5
1000000000 8
"""

aString_list = [x for x in (y.split() for y in aString.split('\n')) if x]
print(aString_list)

we get a result:

[['4', '3'], ['10', '3'], ['100', '5'], ['1000000000', '8']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.