gpt4 book ai didi

python错误太多值无法解包

转载 作者:行者123 更新时间:2023-11-30 23:36:01 25 4
gpt4 key购买 nike

我不明白怎么办"Too many values to unpack" Exception适用于我的问题,如果适用,请解释

回溯:

c:\***>python graphJSON.py
Traceback (most recent call last):
File "graphJSON.py", line 17, in <module>
for region, four, one, two, three, threep in rows:
ValueError: too many values to unpack

我在这段简单的代码中遇到了太多值错误,并且无法弄清楚问题是什么:该错误来自 for 循环。我收到一条消息,说以前有人问过这个问题,但是答案完全不清楚!

rows = csv.reader(open("graph.csv", "rb"))

# Init the the lists that will store our data
regions = []
fourHrs = []
oneDay = []
twoDay = []
threeDay = []
plusThreeDay = []

# Iterate through all the rows in our CSV
for region, four, one, two, three, threep in rows:

regions = regions + [region]
fourHrs = fourHrs + [four]
oneDay = oneDay + [one]
twoDay = twoDay + [two]
threeDay = threeDay + [three]
plusThreeDay = plusThreeDay + [threep]

# Format the output
output = {"data":[{"Regions":regions},
{"Four Hours":fourHrs},
{"One Day":oneDay},
{"Two Days":twoDay},
{"Three Days":threeDay},
{"More than Three Days":plusThreeDay}
]}

生成 JSON 文件json_file = open("graph.json", "w")json.dump(输出,json_file)csv 中的数据如下所示:

First   28  25  10  2   7 
Second 51 17 8 5 15
Third 38 33 24 7 19

已回答:事实证明问题出在 CSV 上,它在一个阶段有更多列,我删除了这些列,但是,我认为在 excel 中引用并没有被完全删除。因此,从 stratch 重做 CSV 后,它成功了!

最佳答案

首先,正如 @Wooble 所指出的,您必须循环遍历 csv 文件中的每一行,而不是遍历 csv 文件本身。

完成后,异常将由以下行引起:

for region, four, one, two, three, threep in rows:

您可以通过异常回溯来确认。

导致该问题的原因是 rows 的项目少于或多于您的代码将其设置为展开的目标项目:

region, four, one, two, three, threep

即少于/多于 6 项。

关于python错误太多值无法解包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16814482/

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