0

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.

0

2 Answers 2

1

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

You have to change second element in the list to integer. Nice solution beside this.
0
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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.