我试图通过要求用户输入文本文件来在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 票数:1

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)

===============>>#2 票数:-1

[编辑]对不起,我以前误解了您的问题,并假设您的输入文件全部位于单独的行中,但我认为它的结构类似于

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函数来做一些事情,例如:

# 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 by eye translate from so

未解决问题?本站智能推荐: