Reputation: 85
I am new to python. I want to read the input from stdin as nested list.
Stdin:
student1 90
student2 85
student3 98
My list should be as follows:
student = [['student1',90],['student2',85],['student3',98]]
Is there any way I can read the input using list comprehension without needing any extra space.
Upvotes: 0
Views: 1600
Reputation: 164693
This is one way.
mystr = 'student1 90\nstudent2 85\nstudent3 98'
[[i[0], int(i[1])] for i in (k.split() for k in mystr.split('\n'))]
# [['student1', 90], ['student2', 85], ['student3', 98]]
Upvotes: 1
Reputation: 4146
my_list = []
while some_condition:
read = input()
my_list.append(read.split())
my_list[-1][1] = int(my_list[-1][1])
Now let's break it down:
EDIT That's what it runs like:
In [1]: my_list = []
...: while True:
...: read = input()
...: my_list.append(read.split())
...: my_list[-1][1] = int(my_list[-1][1])
...: print(my_list)
...:
student 1
[['student', 1]]
student 2
[['student', 1], ['student', 2]]
student 3
[['student', 1], ['student', 2], ['student', 3]]
Upvotes: 0