[英]How to take Nested list as an input.?
如何將下面的列表直接作為 python 的輸入。
a = [[1, 3, 4], [5, 2, 9], [8, 7, 6]]
我是否必須使用 input() function 然后使用 for 循環排列它們,或者有任何方法可以直接將其作為輸入。
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)
我是否必須僅使用此代碼將嵌套列表作為輸入,還是有任何其他直接方法可以將其作為輸入。
您可以使用ast.literal_eval
將嵌套列表直接轉換為 Python object :
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)
出去:
<class 'list'> [[1, 3, 4], [5, 2, 9], [8, 7, 6]]
您可以將較大的部分(或整個內容)作為具有定義語法的字符串輸入。
例如,將每個子列表作為輸入:
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]]
或者整個事情在一起:
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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.