2017-07-08 112 views
0

我想通过要求用户输入文本文件在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) 
+0

不要忘记关闭文件! – PYA

+0

你的文件中有几行对吗? –

回答

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) 
+0

谢谢你,它完美的@cmaher – eye

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

我希望这有助于。