无法从"input(...)"呼叫中解压缩;要解压缩的值太多


ValueError: too many values to unpack.

例如,这一行显然会导致此错误发生,但据我所知,在 Python 3 中可能存在双重分配。

first,second = input('two space-separated numbers:')

我对导致错误的原因没有最模糊的线索。

input返回一个字符串。仅当字符串包含 2 个字符时,解压缩才有效:

>>> first, second = 'ot'
>>> first
'o'
>>> second
't'

否则,它将引发ValueError

>>> first, second = 'asdf'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

但这不是你想要的。使用 str.split 拆分字符串。 按,拆分:

>>> 'hello,world'.split(',')
['hello', 'world']
>>> first, second = 'hello,world'.split(',')  # .split(',', 1)
>>> first
'hello'
>>> second
'world'

按空格拆分:

first, second = input('two space-separated numbers:').split(maxsplit=1)

在 Python 3 中,input 总是返回一个字符串。 尝试将字符串分配给变量列表将导致 Python 将字符串的每个元素(即字符(与变量匹配,如果变量数和字符数不匹配,您将收到一个错误,就像你看到的那样。 您需要解析 input 返回的字符串,以便将其转换为包含两个数字的列表,然后将这些数字分配给 first, second

最新更新