Unpack value(s) into variable(s) or None (ValueError: not enough values to unpack)

Unpack value(s) into variable(s) or None (ValueError: not enough values to unpack)

如何将 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" since Python 3 only. About the 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)
>>>


建议扩展列表:

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

使用 * 运算符并用您要解包的内容填充一个中间可迭代对象,并用您选择的默认值填充其余部分。

x = [1, 2]
default_value= None
one, two, three = [*x, *([default_value] * (3 - len(x)))]

还有处理这两种情况的奖励函数:

def unpack(source, target, default_value=None):
    n = len(source)
    if n < target:
        return [*source, *([default_value] * (target - len(source)))]
    elif n > target:
        return source[0:target]
    else:
        return source

修改以根据需要处理不可迭代的输入。

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

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

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

three = three or None

这对你有用吗?您可以根据需要使 nones 数组变大。

nones = [None]*100 # or however many you think you might need
one, two, three, four, five, *_ = [1,2] + nones