简体   繁体   中英

How to take Nested List as input in Python

I have to take input from the user in the following format and make a nested list from it. The first line is the number of rows.

3  
Sourav Das 24 M  
Titan Das 23 M  
Gagan Das 22 F  

The nested list should be like :

parentlist = [  
['Sourav', 'Das', '24', 'M']  
['Titan', 'Das', '23', 'M']  
['Gagan', 'Das', '22', 'M']  
]  

I have written the following code :

k = int(raw_input())
parentlist = [[]]
for i in range(0, k):
    str1 = raw_input()
    parentlist[i] = str1.split()

But it gives some index out of bound exception after entering the 2nd row (as shown below). What's wrong in the code for which it is giving this exception ?

3
Sourav Das 24 M
Titan Das 23 M
Traceback (most recent call last):
  File "nested.py", line 5, in <module>
    parentlist[i] = str1.split()
IndexError: list assignment index out of range

(I am new to Python. So point out any other mistakes too if you find any in my code.)

When your reading the second line, you attempt to store the splitted line into parentlist[1]. But your parentlist has only one element (parentlist[0]).

The solution is to append the list.

k = int(raw_input())
parentlist = []
for i in range(0, k):
    str1 = raw_input()
    parentlist.append(str1.split())

Your parentlist is a list with one element. On the second iteration for your for loop, you try to access the second element of parentlist , that causes the IndexError. Lists in Python work different from eg arrays in JavaScript or PHP.

What you actually want to do is create an empty list and then append the result of str1.split() to it.

k = int(raw_input())
parentlist = []
for i in range(0, k):
    str1 = raw_input()
    parentlist.append(str1.split())

You should simply use list comprehension as code will be shorter and faster.

k = int(raw_input())
l = []
print [raw_input().split() for i in range(0, k)]

In Python 3:

l= [[input(), float(input())] for _ in range(int(input()))]
print l

Input:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Output:

[[Harry,37.21],[Berry,37.21],[Tina,37.2],[Akriti,41],[Harsh,39]]

You were quite close

k = int(raw_input())
parentlist = []
for i in range(k):
    str1 = raw_input()
    parentlist.append(str1.split())
  • initialize parentlist to an empty list, it is important because later we want to extend it
    • read an input line
    • split the input line -> a list
    • tell the parentlist to append the new list to what it has already got

If you want to go in a bad direction, you can do, similar to your code

parentlist = [[]]*k
for i in range(k):
    parentlist[i] = raw_input().split()

Exercise, find what the syntax [[]]*k stands for...

Size of your parentlist [[]] is 1, where on 0 position empty list. Your code would be work if you put into parentlist k lists:

parentlist = [[]] * k

Or use append instead, but with append additional look up of method name is necessary.

l=[]
for _ in range(int(input())):
    name = input()
    score = float(input())
    l.append([name,score])
print(l)
scorelist =[] 
n = int(input())
for i in range(n):
    name.append(str(input()))
    score.append(float(input()))

for i in range(n):    
    scorelist.append([name[i],score[i]])

print(scorelist)
k = int(input())
parentlist = [None]*k
for i in range(0, k):
    str1 = input()
    parentlist[i] = str1.split()
print(parentlist)

You can also use something like this :-


    k = int(input())
    parentlist = []
    for i in range(k):
        parentlist.append([j for j in input().split()])
    
    print(parentlist)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM