python ValueError:要在元组中解压缩的值太多

Kam*_*ing 2 python json tuples unpack

所以我从json文件中提取数据,我计划将其提供给第三方程序Qanta,这是一个RNN.

好吧,无论如何,我试图以一种方式打包我的数据,所以Qanta的预处理脚本可以使用它.

来自qanta的代码:

for key in split:
    hist = split[key]
    for text, ans, qid in hist:
Run Code Online (Sandbox Code Playgroud)

现在,我从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
Run Code Online (Sandbox Code Playgroud)

所以我有

this = (result,answer,i)
dic[this]=this
Run Code Online (Sandbox Code Playgroud)

当我尝试从qanta复制原始代码时,我得到太多的值来解压错误

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)
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

(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
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我甚至试图限制任务的右侧,但这也没有帮助

正如您所看到的那样输出与每个项目的匹配

hist[0]=This type of year happens once every four
hist[1]=leap
hist[2]=1175
Run Code Online (Sandbox Code Playgroud)

并且len(hist)也返回3.

为什么会发生这种情况?有hist,hist [:3],hist [0:3]具有相同的结果,解包错误的值太多.

J R*_*ape 8

你想要的是什么

text, ans, qid = hist
print(text)
Run Code Online (Sandbox Code Playgroud)

代替

for text, ans, qid in hist:
Run Code Online (Sandbox Code Playgroud)

想想hist代表什么- 它是一个单元组(因为你已经查找过了key)

这意味着

for text, ans, qid in hist:
Run Code Online (Sandbox Code Playgroud)

试图遍历元组的每个成员并将它们分解为这三个组件.所以,首先,它试图在hist [0]上行动,即"今年的这种类型...."并试图将其分解为text,ansqid.Python认识到字符串可以被分解(转换为字符),但无法解决如何将其分解为这三个组件,因为有更多的字符.所以它抛出错误'Too many values to unpack'