将多个数字附加到列表中

时间:2017-07-12 18:04:00

标签: python-2.7 list append

我有一个txt文件中的这一列数字,我想要附加到列表中:

    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]

但是,在运行代码时,它会显示

import sys

filename = '/var/tmp/out3'
expression = 'disk@g5000cca025a1ee6c'

with open(filename, 'r') as f:
with open('p', 'w') as p_file:
    previous = next(f)
    for line in f:
        if expression in line:
            p_file.write(previous)
        previous = line

是否所有数字都可以在一行中。稍后,我想添加所有数字。谢谢你的帮助!!

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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

答案 2 :(得分: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