python ValueError:在tup中解包的值太多

2024-04-26 00:03:42 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我从一个json文件中提取数据,并计划将其输入第三方程序Qanta(一个RNN)。

不管怎样,我试图打包我的数据,以便澳航的预处理脚本可以使用它。

澳航代码:

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

现在,我有一个从json文件中提取的危险问题答案数据集,并将其打包到如下字典中:

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

所以我有

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]的结果相同,值太多,无法解包错误。


Tags: ofthe数据keytextinforis
3条回答

循环要做的是遍历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)

更改此:

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]]:

你想要的是

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'

相关问题 更多 >