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/