Py学习  »  Python

如何在python中输入嵌套列表?

Mihika • 4 年前 • 1384 次点击  

我需要接受以下输入并将其存储在python中的变量中: [1, [2,3]]

我想要类似于下面作业的结果:

l = [1, [2,3]]

但是,接受它作为输入,如下所示将其读取为字符串:

l = input()

是否有任何方法可以接受嵌套列表作为输入,从而使类型保持类“list”而不是类“str”?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43433
 
1384 次点击  
文章 [ 3 ]  |  最新文章 4 年前
user7612258
Reply   •   1 楼
user7612258    5 年前

试试这样的

print("enter the value of i") 
i = [[int(y) for y in x.split("/")]  if "/" in x else int(x) for x in input().split(",") ]
print(i)

输出:

enter the value of i    
1,2,3/4/5,6
[1, 2, [3,4,5],6] 
QuadSI
Reply   •   2 楼
QuadSI    5 年前

def accept(*参数):

     print(args)

你在说什么?

Charles Landau
Reply   •   3 楼
Charles Landau    5 年前

对于几乎所有有效的python,我认为最简单的答案是

your_variable_name = your_python_object
# So with nested list:
your_variable_name = your_nested_list

在函数中,您可以像任何其他输入那样做它:

def nested_list_getter(nested_list):
    # ... your processing of the list here