我正在写一个csv文件,它将数据附加到这样的行中
但是想要这样
我有列表[],我在其中附加数据并使用它来写入文件:
def writefiles(alldata, filename):
with open ("./"+ filename, "w") as csvfile:
csvfile = csv.writer(csvfile, delimiter=",")
csvfile.writerow("")
for i in range(0, len(alldata)):
csvfile.writerow(alldata[i])
writefiles(alldata, "Data.csv")
我怎样才能做到这一点?
最佳答案
您可以使用alldata
将itertools.groupby
转换为所需的格式:
from itertools import groupby, chain
from operator import itemgetter
writefiles([[k, *chain.from_iterable(r for _, *r in g)] for k, g in groupby(alldata, key=itemgetter(0))], "Data.csv")