我想写有不均匀列的行。以下是我的代码:
import csv
import json
path = 'E:/Thesis/thesis_get_data'
outputfile = open('maplight_113.csv', 'w', newline='')
outputwriter = csv.writer(outputfile)
with open (path + "/" + 'maplight data 113congress.json',"r") as f:
data = json.load(f)
for bill in data['bills']:
b = bill.get('measure')
for organization in bill['organizations']:
d = organization.get('name')
f = organization.get('disposition')
a = (organization.get('catcode'))
outputwriter.writerow([b, d, a, f])
outputfile.flush();
每一个" bill.get(' measure')"在我的数据中,可能有一组或多组" d,f,a"来自" bill ['组织']"与之相关联。我希望每一套" d,f,a"在相同的" bill.get(' measure')"中填充其他列。行。
答案 0 :(得分:1)
with open (path + "/" + 'maplight data 113congress.json',"r") as f:
data = json.load(f)
for bill in data['bills']:
b = bill.get('measure')
tmp = [(x.get('name'), x.get('catcode'), x.get('disposition')) for x in bill['organizations']]
outputwriter.writerow(chain((b), *tmp))
outputfile.flush()
你需要:
from itertools import chain