简体   繁体   中英

How to store multi-line input into a list (python)

How would you store a multi-line input into an list?

For example:

3
2 1
1 1 0
2 1 1
4 3 0 1 2
2 
1 2
1 3

How would I take that input and store it as a list like so:

examList = [
      [3],
      [2,1],
      [1,1,0], 
      [2,1,1], 
      [4,3,0,1,2], 
      [2],
      [1,2],
      [1,3]
]

How do you identify the end user input if there any no specific indicators?

Keep calling the input() function until the line it reads in is empty. The use the .split method (no args = space as deliminator). Use a list-comp to convert each string to an int and append this to your examList .

Here's the code:

examList = []
i = input()
while i != '':
    examList.append([int(s) for s in i.split()])
    i = input()

And with your input, examList is:

[[3], [2, 1], [1, 1, 0], [2, 1, 1], [4, 3, 0, 1, 2], [2], [1, 2], [1, 3]]

The above method is for Python3 which allows you to call input() and enter nothing (which is why we use this as a signal to check that we are done - i != '' ).

However, from the docs , we see that, in Python2 , an empty entry to input() throws an EOF error. To get around this, I guess we could just make it so that the multi-line input is ended when the string such as: END is entered. This means that you must stop the entry with a line saying 'END' :

examList = []
i = raw_input()
while i != 'END':
    examList.append([int(s) for s in i.split()])
    i = raw_input()

Note that I've used raw_input as to not perform type conversion.

which works the same as above.

You can use sys.stdin.readlines() .

For example, start with

import sys
user_input = sys.stdin.readlines()

at this point, the value of user_input should be

['3\n', '2 1\n', '1 1 0\n', '2 1 1\n', '4 3 0 1 2\n', '2\n', '1 2\n', '1 3']

then, you should be able to get your desired output by performing the following processing

examList = []

for input_string in user_input:
   examList.append([int(value) for value in input_string.split()])

What we are doing here is iterating through user_input . For each input_string , we split() the words, convert them to int and put them back into a new list. Then, the new list will be added into examList .

Here's an effective one-liner:

>>> inp = '''3
2 1
1 1 0
2 1 1
4 3 0 1 2
2 
1 2
1 3'''
>>> [i.split() for i in inp.split('\n')]

[['3'], ['2', '1'], ['1', '1', '0'], ['2', '1', '1'], ['4', '3', '0', '1', '2'], ['2'], ['1', '2'], ['1', '3']]

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