gpt4 book ai didi

python - 写入 csv 时出现错误 : _csv. 错误:需要序列

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:26 25 4
gpt4 key购买 nike

请帮忙。当我想将 dict AllListInstance 写入 csv 文件时出现错误。这是我的代码:

AllListInstance= {frozenset(['OFFENSE INVOLVING CHILDREN']): [(95,), (96,), (35,), (80,), (100,)], frozenset(['BATTERY', 'THEFT']): [(173, 209), (173, 224)]}

with open('test1.csv', 'wb') as csv_file:
for key in AllListInstance.keys():
csv_writer = csv.writer(csv_file)
csv_writer.writerow(len(AllListInstance[key]))
for y in range(len(key)):
csv_writer.writerow([x[y] for x in key])
csv_writer.writerow(x[y] for x in AllListInstance[key])

预期输出:

5   # len(AllListInstance["OFFENSE INVOLVING CHILDREN"]) count of member
OFFENSE INVOLVING CHILDREN
95
96
35
80
100
2 # len(AllListInstance['BATTERY','THIEF']) count of member
BATTERY THIEF
173 209
173 224

错误:

    csv_writer.writerow(len(AllListInstance[key]))
_csv.Error: sequence expected

我的预期输出的解决方案:

with open('test8.csv', 'wb') as csv_file:
for key in AllListInstance.keys():
csv_writer = csv.writer(csv_file)
csv_writer.writerow([len(key),len(AllListInstance[key])])
csv_writer.writerow(list(key))
for x in AllListInstance[key]:
csv_writer.writerow(list(x))

最佳答案

您正在传递一个单个整数:

len(AllListInstance[key])

这不是一个序列,这是 csv_writer.writerow() 所期望的。如果您想写入带有长度值的一列,请将其包装在列表中:

csv_writer.writerow([len(AllListInstance[key])])

关于python - 写入 csv 时出现错误 : _csv. 错误:需要序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34822252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com