在python中追加列表以创建嵌套列表

在python中追加列表以创建嵌套列表,python,list,append,Python,List,Append,我试图在Python中创建一个嵌套列表,要求用户输入文本文件。 输入文件如下所示: 1.32.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 th

我试图在Python中创建一个嵌套列表,要求用户输入文本文件。 输入文件如下所示:

1.32.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.32.6 3.2 4.1
1 -3 2 
-4.1

如果您只是询问如何将列表附加到列表中,以在Python中创建嵌套列表,那么以下是您的操作方法:

list1 = [1,2,3,4]
list2 = [5,6,7,8]
nested_list = []
nested_list.append(list1)
nested_list.append(list2)
这将导致:

[[1,2,3,4],[5,6,7,8]

我认为上面的答案给出了一个非常简洁的答案,包含了列表的理解,但是你也可以用lambda函数做一些事情,比如:

# Ask the user to input a file name
file_name = input("Enter the Filename: ")

nlist = []

# Opening the file to read the content
with open(file_name, 'r') as infile:
    for line in infile:
        ls = list(map(lambda x: float(x), line.split()))
        nlist.append(ls)

print(nlist)
此外,您还可以将其缩短为一行:

# Ask the user to input a file name
file_name = input("Enter the Filename: ")

# Opening the file to read the content
with open(file_name, 'r') as infile:
    ls = list(map(lambda line: list(map(lambda x: float(x), line.split())), infile))

我希望这有帮助。

别忘了关闭文件!您的文件中有几行,对吗?
# Ask the user to input a file name
file_name = input("Enter the Filename: ")

# Opening the file to read the content
with open(file_name, 'r') as infile:
    ls = list(map(lambda line: list(map(lambda x: float(x), line.split())), infile))