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

2024-09-30 03:23:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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)

Tags: theto代码namein列表forinput
2条回答

[编辑] 抱歉,我之前误解了您的问题,并假设您的输入文件都在单独的行中,但我认为它的结构如下

1.3 2.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函数做一些事情:

^{pr2}$

此外,您甚至可以将其缩短为一行:

# 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))

我希望这有帮助。在

file_name=input("Enter the Filename: ")

# use "with" block to open file
# to ensure the file is closed once your code is done with it
with open(file_name,'r') as infile:
  # create "nlist" here and append each element to it during iteration
  nlist=[]
  for line in infile:
    line_str=line.split()
    # no need to iterate with range(len()); use a list comprehension
    # to map "float" to each list element
    line_str = [float(element) for element in line_str]  
    nlist.append(line_str)
  print(nlist)

相关问题 更多 >

    热门问题