简体   繁体   中英

Reading multiple lines with input()

Sample input 1:

1 10
100 200
201 210
900 1000

Sample input 2:

4 49
2 59

So I don't know how many lines the input would be, and I want to organize the input into a 2d array. The lines are submitted all at once (no multiple input() ).

Edit: Sorry I'm terrible with I/O. Here's what I want:

nums = []
for i in range(0,endofinput):
    nums.append(list(map(int, input().split())))
print(nums)

Problem is, I don't know how many inputs there will be. I don't have control over the input, so I can't just make a while loop to detect when the next input is "". Is there possibly a way to know how many lines of input I will be getting?

How much control do you have over the format of the input? (Is it coming from some external automated system? From a User? From another script?)

Assuming you have some measure of control, you can implement a sentinel value, such as an empty line, to detect the end of the input. Then

l = []
data = input(':')
while data:
    l.append(list(map(int, data.split())))

will read lines of whitespace-separated integers into a list of lists of integers until it reads an empty line.

Usually, input() accepts single lines only. The only way I know to pass multiple lines is to paste a copied block of text. The program processes the lines as if they had been entered one by one. The only way to tell your program that the end of the input has been reached is to enter either some stop-code or, more stylish, to press Ctrl-D, the classic End-Of-File marker.

print("Enter multiple lines, press Ctrl-D after last line:")
Array=[]
while True:
    try:
        Array.append([int(a) for a in input().split(" ")])
    except EOFError:
        print(len(Array),"lines of data have been received.")
        break

Result after pasting four lines and pressing [Enter] and [Ctrl-D]:

Enter multiple lines, press Ctrl-D after last line:
1 10
100 200
201 210
900 1000
4 lines of data have been received.
>>> Array
[[1, 10], [100, 200], [201, 210], [900, 1000]]
>>>         

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