-1

I want to read the inputs line by line for n element and i would want them to be inside a nested list. for 3 elements Input:

Anna
1
Hath
2
Nick
3

Expected output

[["Anna",1]["Hath",2]["Nick",3]]

I planned to run a for loop of n*2 to take the inputs for 6 elements, but every 2 element i wanted to create a list, and all these seperate lists would be a part of a bigger list.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
Srinabh
  • 400
  • 5
  • 13
  • 4
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem individually. A good way to show this effort is to include a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Check the [intro tour](https://stackoverflow.com/tour) you finished before posting, especially [How to Ask](http://stackoverflow.com/help/how-to-ask). – Prune Aug 29 '18 at 17:56
  • 2
    Start off by looping over each line in the file: `for line in file:`. Make sure you did `open('file.txt', 'r')` first – N Chauhan Aug 29 '18 at 18:00
  • @NChauhan I don't think they are talking about a file – Joe Iddon Aug 29 '18 at 18:03
  • @NChauhan But I added it anyway :) – Joe Iddon Aug 29 '18 at 18:06

1 Answers1

3

Just use a list-comprehension with range:

n = 3
[[input(), int(input())] for _ in range(n)]
#[['Anna', '1'], ['Hath', '2'], ['Nick', '3']]

If you are talking about reading from a file (rather than stdin) then just open the file first, and then use readline() on the file-object in place of input():

n = 3
with open('your_file') as f:
    [[f.readline(), int(f.readline())] for _ in range(n)]

side note: if you are not familiar with the convention, the underscore (_) is used as a placeholder when the variable is not needed in a for-loop

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • Maybe do an `int()` call on the second input? (assuming input is always consistent) – N Chauhan Aug 29 '18 at 18:08
  • @NChauhan Good idea. – Joe Iddon Aug 29 '18 at 18:09
  • I just updated it with what i have tried, please tell me if there is a way to map reverse to sorting multiple elements – Srinabh Aug 29 '18 at 18:34
  • @Srinabh You should ask a new question, but fortunately for you, that question has already been asked here: https://stackoverflow.com/questions/6666748/python-sort-list-of-lists-ascending-and-then-decending. Please accept this answer as I will revert the question back to how it was originally asked, this ask is something different from the original ask. – Joe Iddon Aug 29 '18 at 19:02