在python中逐行读取文本文件作为浮点列表

时间:2015-03-01 10:48:22

标签: python

关于Python的问题。我有一个txt文件:

[1,2,3,4,5]
[6,7,8,9,10]
[11,12,13,14,15]
[16,17,18,19,20]
[21,22,23,24,25]

此处的每个列表都是文件中的新行。我想逐行读取文件,但是每行应该是python列表,换句话说,如果我为第一行写例如print list1 [0],list [0]必须给1.当我写下面的代码时: 结果就是角色" ["。这意味着内容不是列表。如何获得列表[0],因为它给出1?

#!/usr/bin/python
# -*- coding: utf 8 -*-
import os
import sys
import math
import matplotlib
with open("grafik.txt") as f:
    list = f.read()
    print list[0]
if __name__ == "__main__":
    pass

2 个答案:

答案 0 :(得分:3)

您有字符串而不是列表,您希望使用ast.literal_eval转换为实际列表:

from ast import literal_eval
with open("grafik.txt") as f:
    for line in f:
        lst = literal_eval(line)
        print(lst)
        print(type(lst))

 <class 'list'>
[6, 7, 8, 9, 10]
<class 'list'>
[11, 12, 13, 14, 15]
<class 'list'>
[16, 17, 18, 19, 20]
<class 'list'>
[21, 22, 23, 24, 25]
<class 'list'>

如果您想要列表,请将代码更改为:

 lsts = [literal_eval(line) for line in f]
 print(lsts)

如果你真的想要漂浮物出于某种原因你可以用map来改变浮点数但除非你特别需要浮点数我不会打扰

lsts = [map(float, literal_eval(line)) for line in f] # list(map... python3
print(lsts)

答案 1 :(得分:0)

你也可以这样做。

with open('file') as f:
    fil = f.readlines()
    m = (line.replace('[', '').replace(']', '').strip().split(',') for line in fil)
    for line in m:
        print(line)

import re
with open('file') as f:
    for line in f:
        print(re.findall('\d+', line))

输出:

['1', '2', '3', '4', '5']
['6', '7', '8', '9', '10']
['11', '12', '13', '14', '15']
['16', '17', '18', '19', '20']
['21', '22', '23', '24', '25']