如何将元组解压缩为比元组更多的值?

How to unpack a tuple into more values than the tuple has?

我有一个元组列表,每个元组包含 1 到 5 个元素。我想将这些元组解压缩为五个值,但这不适用于少于五个元素的元组:

>>> t = (1,2) # or (1) or (1,2,3) or ...
>>> a,b,c,d,e = (t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

可以将不存在的值设置为 None。基本上,我正在寻找一种更好(更密集)的方法,如果这个函数:

def unpack(t):
    if len(t) == 1:
        return t[0], None, None, None, None
    if len(t) == 2:
        return t[0], t[1], None, None, None
    if len(t) == 3:
        return t[0], t[1], t[2], None, None
    if len(t) == 4:
        return t[0], t[1], t[2], t[3], None
    if len(t) == 5:
        return t[0], t[1], t[2], t[3], t[4]
    return None, None, None, None, None

(这道题和this one or this one有些相反。)

您可以添加剩余的元素:

a, b, c, d, e = t + (None,) * (5 - len(t))

演示:

>>> t = (1, 2)
>>> a, b, c, d, e = t + (None,) * (5 - len(t))
>>> a, b, c, d, e
(1, 2, None, None, None)