Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting input (from stdin) into lists

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']
like image 273
Noob Coder Avatar asked Oct 05 '13 21:10

Noob Coder


People also ask

How do you convert input to a list in Python?

Get a list of numbers as input from a user. Use an input() function to accept the list elements from a user in the format of a string separated by space. Next, use a split() function to split an input string by space. The split() method splits a string into a list.

Is input () the stdin Python?

Python sys module stdin is used by the interpreter for standard input. Internally, it calls the input() function. The input string is appended with a newline character (\n) in the end.

How do you read two integers from stdin in Python?

Read two integers from STDIN and print three lines where: The first line contains the sum of the two numbers. The second line contains the difference of the two numbers (first - second). The third line contains the product of the two numbers. print (sum) #The first line contains the sum of the two numbers.


2 Answers

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 ...
like image 161
juliomalegria Avatar answered Oct 15 '22 20:10

juliomalegria


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.

like image 3
Óscar López Avatar answered Oct 15 '22 18:10

Óscar López