python - 将值解压到变量中或无(ValueError : not enough values to unpack)

标签 python iterable-unpacking

iterable应该如何被解包成数量不匹配的变量?

值太多:

>>> one,two = [1,2,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

可以忽略

>>> one,two,*_ = [1,2,3,4]  
>>> 

注意:“extended iterable unpacking ”仅自 Python 3 起。关于underscore .

数据太少/变量较多的相反情况如何:

>>> one,two,three = [1,2]   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>

进行处理,特别是为剩余的变量分配 None (或其他值)?

类似这样的事情:

>>> one,two,three = [1,2] or None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>

<小时/> https://stackoverflow.com/a/8857846/1619432建议扩大列表:

>>> one,two,three = [1,2] + [None]*(3-2)
>>> one   
1
>>> two
2
>>> three
>>>

最佳答案

您可以使用以下方法将序列解压缩为三个变量:

one, two, *three = [1,2]

此时,two 将是一个空列表。然后,您可以使用 or 检查 3 是否为空,将 two 分配给 None

three = three or None

关于python - 将值解压到变量中或无(ValueError : not enough values to unpack),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59303232/

相关文章:

python - 如何使用 WordNet 查找英语单词的频率计数?

python - 非空 gcs 存储桶返回 "can only concatenate str (not "字节") 到 str"

python - 在 colab 中运行 jupyter 笔记本

python - 如何捕获tcp请求包?

python - 如何解压列表?

python - 为什么分配给一个空列表而不是一个空元组是有效的?

python - 解包到Python中的list append方法

python - 在字符级别对文本进行编码以输入 tensorflow 模型的最有效和高效的方法是什么?

python - 仅从 Python 中的单元素列表中获取元素?