Python ValueError: 元组中的值过多

5

我正在从一个JSON文件中提取数据。

我试图以一种方式打包我的数据,以便预处理脚本可以使用它。

预处理脚本代码:

for key in split:
    hist = split[key]
    for text, ans, qid in hist:

现在我有一个提取出来的数据集,格式如下所示:Dictionary。
dic{}
result //is the result of removing some formatting elements and stuff from the Question, so is a question string
answer //is the answer for the Q
i // is the counter for Q & A pairs

So I have

this = (result,answer,i)
dic[this]=this

当我尝试复制原始代码时,出现了“值过多无法解包”的错误。
for key in dic:
    print(key)
    hist = dic[key]
    print(hist[0])
    print(hist[1])
    print(hist[2])
    for text, ans, qid in hist[0:2]:  // EDIT: changing this to hist[0:3] or hist has no effect
        print(text)

输出:

(u'This type of year happens once every four', u'leap', 1175)
This type of year happens once every four
leap
1175
Traceback (most recent call last):
  File "pickler.py", line 34, in <module>
    for text, ans, qid in hist[0:2]:
ValueError: too many values to unpack

正如您所看到的,我甚至尝试限制赋值的右侧,但那也没有帮助

而且,正如您所看到的,每个项目的输出都与应该匹配的一样

hist[0]=This type of year happens once every four
hist[1]=leap
hist[2]=1175

而 len(hist) 也返回 3。

为什么会这样?具有 hist、hist[:3] 和 hist[0:3] 相同的结果,会导致“要解包的值过多”错误。


1
请问您能否纠正一下示例代码的缩进级别,这样我们就可以看到代码块了吗?谢谢! - Klaus D.
3个回答

13
您需要的是:
text, ans, qid = hist
print(text)

替代

for text, ans, qid in hist:

考虑一下 hist 代表什么 - 这是一个单独的元组(因为你已经用 key 查找它)

这意味着

for text, ans, qid in hist:

代码试图遍历元组中的每个成员,并将它们分解为这三个组件。所以首先,它尝试对hist[0]即“这种类型的年份....”进行操作,并尝试将其分解为textansqid。Python认识到该字符串可以被拆分(成字符),但无法确定如何将其分解为这三个组件,因为其中有更多的字符。因此,它会报错'Too many values to unpack'


相同的结果 @JRichardSnape - KameeCoding
抱歉 - 我掉进了一个非常愚蠢的陷阱 - 请查看修订后的答案。另外请注意 - @rchang 是对的 - 他没有建议您迭代 hist[0:3]。 - J Richard Snape
感谢清晰解释拆包错误的来源。 :) - rchang

2
您的循环尝试遍历 `hist` 的前三个项目,并将每个项目都单独解释为一个包含三个元素的元组。我猜您想要做的是这样的:
for key in dic:
    hist = dic[key]
    (text, ans, qid) = hist[0:3] # Might not need this slice notation if you are sure of the number of elements
    print(text)

@Kameegaming 我尽可能在这里复制了你的情况:http://repl.it/8aC(点击“运行会话”)。我有遗漏什么吗? - rchang
看起来没问题,这个确实有效,即使我不加上 [0:3],但是用 for 循环就不行,这很奇怪,嗯 - KameeCoding
好的回答。请看我的稍微长一点的回答,了解为什么它不能与“for”一起使用。 - J Richard Snape

2

改变这个:

for text, ans, qid in hist[0:2]:

转换为:

for text, ans, qid in hist[0:3]:

hist[x:y]表示从hist中所有满足x <= ids < y的元素

编辑:

正如@J Richard Snape和@rchang所指出的,你不能使用这个:

for text, ans, qid in hist[0:3]:

但是你可以使用这个替代方案(对我有效):
for text, ans, qid in [hist[0:3]]:

相同的结果 @JasonPap - KameeCoding

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接