ValueError: 需要 1 个以上的值才能解包,拆分一行

use*_*660 3 python

我在同一行有一个包含问题和答案的文件,我想将它们分开并将它们附加到自己的空列表中,但不断收到此错误:
builtins.ValueError: need more than 1 value to unpack

questions_list = []
answers_list = []

questions_file=open('qanda.txt','r')


for line in questions_file:
    line=line.strip()

    questions,answers =line.split(':')

    questions_list.append(questions)
    answers_list.append(answers)
Run Code Online (Sandbox Code Playgroud)

Gam*_*iac 5

这可能是因为当您进行拆分时,没有:,因此该函数只返回一个参数,而不是 2。这可能是由最后一行引起的,这意味着您的最后一行只有空格。像这样:

>>> a = '   '
>>> a = a.strip()
>>> a
''
>>> a.split(':')
['']
Run Code Online (Sandbox Code Playgroud)

如您所见,从返回的列表.split只是一个空字符串。所以,只是为了向您展示一个演示,这是一个示例文件:

a: b
c: d
e: f

g: h
Run Code Online (Sandbox Code Playgroud)

我们尝试使用以下脚本(val.txt是上述文件的名称):

with open('val.txt', 'r') as v:
    for line in v:
        a, b = line.split(':')
        print a, b
Run Code Online (Sandbox Code Playgroud)

这给了我们:

Traceback (most recent call last):
a  b

c  d
  File "C:/Nafiul Stuff/Python/testingZone/28_11_13/val.py", line 3, in <module>

    a, b = line.split(':')
e  f
ValueError: need more than 1 value to unpack
Run Code Online (Sandbox Code Playgroud)

当尝试通过调试器查看此变量line\n,变量变为,并且您无法拆分它。

然而,一个简单的逻辑修正,将纠正这个问题:

with open('val.txt', 'r') as v:
    for line in v:
        if ':' in line:
            a, b = line.strip().split(':')
            print a, b
Run Code Online (Sandbox Code Playgroud)


Kos*_*Kos 5

尝试:

question, answers = line.split(':', maxsplit=1)
question, __, answers = line.partition(':')
Run Code Online (Sandbox Code Playgroud)

同样在 Python 3 中你还可以做其他事情:

question, *many_answers = line.split(':')
Run Code Online (Sandbox Code Playgroud)

看起来像:

temp = line.split(':')
question = temp[0]
many_answers = tuple(temp[1:])
Run Code Online (Sandbox Code Playgroud)