繁体   English   中英

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

[英]How to read lists of list from a file and make individual lists?

我在这里有一个文件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]]', '']

尝试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM