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

Jen*_*ens 5 python tuples python-3.x iterable-unpacking

我有一个元组列表,每个元组包含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
Run Code Online (Sandbox Code Playgroud)

可以将不存在的值设置为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
Run Code Online (Sandbox Code Playgroud)

(这个问题与这一个这个问题有些相反.)

Mar*_*ers 11

您可以添加其余元素:

a, b, c, d, e = t + (None,) * (5 - len(t))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> t = (1, 2)
>>> a, b, c, d, e = t + (None,) * (5 - len(t))
>>> a, b, c, d, e
(1, 2, None, None, None)
Run Code Online (Sandbox Code Playgroud)