2017-07-12 87 views
0

我有一个txt的文件编号本栏认为我要追加到一个列表:多个号码添加到列表中

18.0 
13.0 
10.0 
12.0 
8.0 

我对将所有这些数字为代码列表

last_number_lis = [] 
    for numbers_to_put_in in (path/to/txt): 
     last_number_lis.append(float(last_number)) 
    print last_number_lis 

我想要列表看起来像

[18.0,13.0,10.0,12.0,8.0] 

而是,当运行代码时,它显示

[18.0] 
[13.0] 
[10.0] 
[12.0] 
[8.0] 

有没有什么办法可以把所有的号码放在一行中。稍后,我想将所有数字都加上。谢谢你的帮助!!

+1

您可以张贴整个代码? – Dadep

+1

请出示完整的代码。 – victor

+0

@Dadep我发布的代码的一部分,因为总的脚本有200行。 –

回答

0

可以append列表就像:

>>> list=[] 
>>> list.append(18.0) 
>>> list.append(13.0) 
>>> list.append(10.0) 
>>> list 
[18.0, 13.0, 10.0] 

但取决于您的号码是从哪里来的?

例如与输入端子:

>>> list=[] 
>>> t=input("type a number to append the list : ") 
type a number to append the list : 12.45 
>>> list.append(float(t)) 
>>> t=input("type a number to append the list : ") 
type a number to append the list : 15.098 
>>> list.append(float(t)) 
>>> list 
[12.45, 15.098] 

或阅读从文件:

>>> list=[] 
>>> with open('test.txt', 'r') as infile: 
...  for i in infile: 
...    list.append(float(i)) 
... 
>>> list 
[13.189, 18.8, 15.156, 11.0] 
0

如果是从.txt文件,你必须做的readline()方法,

你可以通过号码列表for循环和循环做了(你永远不知道你会多少个号码给出还不如让循环处理它,

with open(file_name) as f: 
    elemts = f.readlines() 
    elemts = [x.strip() for x in content] 

,然后你会想通过文件循环,然后在列表

last_number_list = [] 
for last_number in elements: 
    last_number_list.append(float(last_number)) 
print last_number_list 
0

一个稍微不那么紧凑,但容易阅读的方法是添加元素

num_list = [] 
f = open('file.txt', 'r') # open in read mode 'r' 
lines = f.readlines() # read all lines in file 
f.close() # safe to close file now 
for line in lines: 
    num_list.append(float(line.strip())) 
print num_list