如何从文件中读取列表列表并创建单个列表?

时间:2019-04-08 18:56:06

标签: python python-3.x numpy

我在https://www.dropbox.com/s/mwz8s2kap2mnwo0/data.dat?dl=0处有一个文件,其中每一行都是元素数量不同的列表的列表。我想从上面文件中给出的数据中创建两个单独的列表,说A和B,其中A包含诸如[3,3,1],[3,3,1],[3,3,3 ,1],[3、3、3、1]和B包含元素[5.55,4.786504465682655,4.786504465682655],[4.801464620300768,4.786504465682655,4.801464620300768]等。

我首先尝试从文件中读取数据,如下所示:

with open('data.dat', 'r') as f:
     x = f.read().splitlines()
x

这给了我以下输出:

['[[3, 3, 1], [5.55, 4.786504465682655, 4.786504465682655]]',
 '[[3, 3, 1], [4.801464620300768, 4.786504465682655, 4.801464620300768]]',
 '[[3, 3, 3, 1], [2.7663717212261982, 2.7663717212261982, 2.7663717212261982, 5.5327434424523965, 2.775, 4.786504465682655]]',
 '[[3, 3, 3, 1], [2.775, 2.775, 4.801464620300768, 3.9244426355853386, 4.801464620300768, 4.801464620300768]]',
 '']

从这里我不确定如何继续前进并分离两个列表并将它们附加到两个不同的列表中。任何帮助深表感谢!

编辑:如果我在导入ast

之后仅添加另一行
x = ast.literal_eval(x)

提供以下输出:

/anaconda3/lib/python3.6/ast.py in _convert(node)
     82                 else:
     83                     return left - right
---> 84         raise ValueError('malformed node or string: ' + repr(node))
     85     return _convert(node_or_string)
     86 

ValueError: malformed node or string: ['[[3, 3, 1], [5.55, 4.786504465682655, 4.786504465682655]]', '[[3, 3, 1], [4.801464620300768, 4.786504465682655, 4.801464620300768]]', '[[3, 3, 3, 1], [2.7663717212261982, 2.7663717212261982, 2.7663717212261982, 5.5327434424523965, 2.775, 4.786504465682655]]', '[[3, 3, 3, 1], [2.775, 2.775, 4.801464620300768, 3.9244426355853386, 4.801464620300768, 4.801464620300768]]', '']

1 个答案:

答案 0 :(得分:1)

尝试一下:

A, B = [], []

for i in x:
    if not i: # for ''
        continue
    tmp_list = ast.literal_eval(i)
    A.append(tmp_list[0])
    B.append(tmp_list[1])

打印A,B

A: [[3, 3, 1], [3, 3, 1], [3, 3, 3, 1], [3, 3, 3, 1]]
B: [[5.55, 4.786504465682655, 4.786504465682655], [4.801464620300768, 4.786504465682655, 4.801464620300768], [2.7663717212261982, 2.7663717212261982, 2.7663717212261982, 5.5327434424523965, 2.775, 4.786504465682655], [2.775, 2.775, 4.801464620300768, 3.9244426355853386, 4.801464620300768, 4.801464620300768]]