Converting input (from stdin) into lists

33,045

Solution 1

Use split to split a string into a list, for example:

>>> '2 2 4 5 7'.split()
['2', '2', '4', '5', '7']

As you see, elements are string. If you want to have elements as integers, use int and a list comprehension:

>>> [int(elem) for elem in '2 2 4 5 7'.split()]
[2, 2, 4, 5, 7]

So, in your case, you would do something like:

import sys

list_of_lists = []

for line in sys.stdin:
    new_list = [int(elem) for elem in line.split()]
    list_of_lists.append(new_list)

You will end up having a list of lists:

>>> list_of_lists
[[3], [2], [2, 2, 4, 5, 7]]

If you want to have those lists as variables, simply do:

list1 = list_of_lists[0]  # first list of this list of lists
list1 = list_of_lists[1]  # second list of this list of lists
list1 = list_of_lists[2]  # an so on ...

Solution 2

Here's one way:

import ast
line = '1 2 3 4 5'
list(ast.literal_eval(','.join(line.split())))
=> [1, 2, 3, 4, 5]

The idea is, that for each line you read you can turn it into a list using literal_eval(). Another, shorter option would be to use list comprehensions:

[int(x) for x in line.split()]
=> [1, 2, 3, 4, 5]

The above assumes that the numbers are integers, replace int() with float() in case that the numbers have decimals.

Share:
33,045
Noob Coder
Author by

Noob Coder

Noob learning to code.

Updated on October 06, 2020

Comments

  • Noob Coder
    Noob Coder over 3 years

    I need to convert input(series of integers) into a bunch of lists.

    Sample Input:

    3
    2
    2 2 4 5 7
    

    Sample Output:

    list1=[3]
    list2=[2]
    list3=[2,2,4,5,7]
    

    I am trying to do this:

    list=[]
    import sys
    for line in sys.stdin:
        list.append(line)
    

    but print list returns

    ['3\n', '2\n', '2 2 4 5 7']
    
  • Noob Coder
    Noob Coder over 10 years
    This works! But if I want to break down that list into three separate lists, would I just name the 3 lists beforehand and repeat the above?