我有一个嵌套列表作为使用split()完成的操作的结果。如何将此输出转换为单个列表并写入文件
["['48999', '19:09:11', 'R', 'qp32']", "['49054', '00:24:42', 'R', 'qp32']", "['49151', '0', 'Q', 'batch']", "['49173', '332:05:4', 'R', 'qp128']", "['49174', '179:22:4', 'R', 'qp256']"]
文件输出应该是这样的
48999 19:09:11 R qp32
49054 00:24:42 R qp32
49151 0 Q batch
依此类推,直到列表的所有条目都输入到文件
中编辑: 内容是
['48999.tyrone-cluster;gic2_nwgs;mbupi;19:09:11;R;qp32\n', '49054.tyrone-cluster;...01R-1850-01_2;mcbkss;00:24:42;R;qp32\n', '49151.tyrone-cluster;gic7_nwgs;mbupi;0;Q;batch\n', '49173.tyrone-cluster;jet_egrid;asevelt;332:05:4;R;qp128\n', '49174.tyrone-cluster;jet_egrid;asevelt;179:22:4;R;qp256\n']
for item in [s.split(";") for s in content]:
parsed_data = [item[0].split(".")[0], item[3], item[4], item[5].strip()]
print >>f,parsed_data
从文件中读取数据后,列表的输出将为
["['48999', '19:09:11', 'R', 'qp32']\n", "['49054', '00:24:42', 'R', 'qp32']\n", "['49151', '0', 'Q', 'batch']\n", "['49173', '332:05:4', 'R', 'qp128']\n", "['49174', '179:22:4', 'R', 'qp256']\n"]
答案 0 :(得分:4)
您可以使用ast.literal_eval
将字符串元素转换为列表对象,然后写入文件:
import ast
l=["['48999', '19:09:11', 'R', 'qp32']", "['49054', '00:24:42', 'R', 'qp32']", "['49151', '0', 'Q', 'batch']", "['49173', '332:05:4', 'R', 'qp128']", "['49174', '179:22:4', 'R', 'qp256']"]
with open('my_file.txt','w') as f:
for li in [ast.literal_eval(i) for i in l]:
f.write(' '.join(li)+'\n')
my_file.txt:
48999 19:09:11 R qp32 49054 00:24:42 R qp32 49151 0 Q batch 49173 332:05:4 R qp128 49174 179:22:4 R qp256
答案 1 :(得分:2)
ast.literal_eval
和csv
模块将获得您需要的输出:
l =["['48999', '19:09:11', 'R', 'qp32']", "['49054', '00:24:42', 'R', 'qp32']", "['49151', '0', 'Q', 'batch']", "['49173', '332:05:4', 'R', 'qp128']", "['49174', '179:22:4', 'R', 'qp256']"]
from ast import literal_eval
import csv
with open("out.csv","w") as f:
wr = csv.writer(f,delimiter=" ")
for row in l:
wr.writerow(literal_eval(row))
输出:
48999 19:09:11 R qp32
49054 00:24:42 R qp32
49151 0 Q batch
49173 332:05:4 R qp128
49174 179:22:4 R qp256
答案 2 :(得分:0)
只需添加选项,您还可以使用方便的模块pyparser进行这些类型的解析。