keerthana
keerthana

Reputation: 85

Read input as nested list in python

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

Answers (2)

jpp
jpp

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

gonczor
gonczor

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:

  1. Create an empty list,
  2. Keep on reading from stdin (you get str here)
  3. add read element to your list by splitting it (it will create a new list).
  4. Turn second element of last inserted item to integer.

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

Related Questions