我试图在Python中创建一个嵌套列表,方法是让用户输入文本文件。 输入文件如下:
1.3 2.6 3.2 4.1
1 -3 2
-4.1
最后,输出应为: [[1.3,2.6,3.2,4.1],[1.0,-3.0,2.0],[-4.1]]
我的代码可以一个接一个地显示单个列表,但在附加列表时遇到困难。 由于我是python的新手,任何帮助都是非常感谢的。提前谢谢。 我的代码如下:
#Ask the user to input a file name
file_name=input("Enter the Filename: ")
#Opening the file to read the content
infile=open(file_name,'r')
#Iterating for line in the file
for line in infile:
line_str=line.split()
for element in range(len(line_str)):
line_str[element]=float(line_str[element])
nlist=[[] for line in range(3)]
nlist=nlist.append([line_str])
print(nlist)
[编辑] 抱歉,我之前误解了您的问题,并假设您的输入文件都在单独的行中,但我认为它的结构如下
1.3 2.6 3.2 4.1 1 -3 2 -4.1
如果您只是询问如何在Python中向列表追加一个列表以创建嵌套列表,那么您可以这样做:
这将导致:
[ [1,2,3,4] , [5,6,7,8] ]
我认为上面的答案用列表理解给出了一个相当简洁的答案,但是您也可以用lambda函数做一些事情:
^{pr2}$此外,您甚至可以将其缩短为一行:
我希望这有帮助。在
相关问题 更多 >
编程相关推荐