Python: 读取列表转换为字符串的文件并转换回列表

Python: read a file with lists converted to strings and convert back to lists

我有一个 txt 文件,如下所示:

0.41,"[1.0, 0.0, 1.0]","[16.4, 0.0, 0.0]"    
0.23,"[0.0, 2.0, 2.0]","[32.8, 0.0, 0.0]"    
0.19,"[0.0, 0.0, 3.0]","[92.8, 0.0, 0.0]"   

我希望阅读它并将字符串转换为列表:

a=[0.41, 0.23, 0.19, 0.03, 0.02, 0.02]    
b=[[1.0, 0.0, 1.0],[0.0, 2.0, 2.0],[0.0, 0.0, 3.0]]    
c=[[16.4, 0.0, 0.0],[32.8, 0.0, 0.0],[92.8, 0.0, 0.0]]     

如何在 python 中执行此操作?

提前致谢,

我会使用 csv 模块来正确标记项目,然后我会使用 zip 转置行并将字符串数据转换为 python lists/values 使用ast.literal_eval

import csv
import ast


with open("file.txt") as f:
   cr = csv.reader(f)
   items = [[ast.literal_eval(x) for x in row] for row in zip(*cr)]

print(items)

结果:列表列表

[[0.41, 0.23, 0.19], [[1.0, 0.0, 1.0], [0.0, 2.0, 2.0], [0.0, 0.0, 3.0]], [[16.4, 0.0, 0.0], [32.8, 0.0, 0.0], [92.8, 0.0, 0.0]]]

这不是一般情况,但如果您知道列表中正好有 3 个项目,则可以将它们解包到您想要的任何变量:

if len(items)==3:
    a,b,c = items
    print(a)
    print(b)
    print(c)

你得到:

[0.41, 0.23, 0.19]
[[1.0, 0.0, 1.0], [0.0, 2.0, 2.0], [0.0, 0.0, 3.0]]
[[16.4, 0.0, 0.0], [32.8, 0.0, 0.0], [92.8, 0.0, 0.0]]

请注意,对于给定的输入数据,a 您的预期输入是不可能的。