how can I take this list below as an input in python directly.
a = [[1, 3, 4], [5, 2, 9], [8, 7, 6]]
Do I have to use input() function and then arrange them using a for loop or there is any method to take it directly as input.
x=int(input("enter the size of list"))
y= int(input("enter the size of sublist"))
list1=[]
sublist=[]
for i in range(x):
for j in range(y):
sublist.append(input())
list1.append(sublist)
sublist=[]
print (list1)
Do I have to use this code only to take nested list as input or there is any other direct method to take it as input.
CodePudding user response:
You could make use of ast.literal_eval
to convert the nested list into Python object directly:
import ast
#data = input("enter nested list")
data = "[[1, 3, 4], [5, 2, 9], [8, 7, 6]]"
list1 = ast.literal_eval(data)
print(type(list1), list1)
Out:
<class 'list'> [[1, 3, 4], [5, 2, 9], [8, 7, 6]]
CodePudding user response:
You could take larger parts (or the whole thing) as a string input with defined syntax.
e.g. Take each sublist as an input:
x=int(input("enter the size of list"))
list1=[]
for i in range(x):
sublist = input(f"Enter sublist {i 1} as comma separated values")
sublist = [int(v) for v in sublist.split(",")]
list1.append(sublist)
print (list1)
Output:
enter the size of list
3
Enter sublist 1 as comma separated values
1,3,4
Enter sublist 2 as comma separated values
5,2,9
Enter sublist 3 as comma separated values
8,7,6
[[1, 3, 4], [5, 2, 9], [8, 7, 6]]
Or the whole thing together:
list1=input("Enter your list of lists using a space to separate the sublists and a comma to separate the values of the sublist. e.g. 1,2,4 8,2,1 9,1,0")
list1= [[int(v) for v in sublist.split(",")] for sublist in list1.split(" ")]
print (list1)
Output:
Enter your nested list using a space to separate the sublists and a comma to separate the values of the sublist. e.g. 1,2,4 8,2,1 9,1,0
1,3,4 5,2,9 8,7,6
[[1, 3, 4], [5, 2, 9], [8, 7, 6]]