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

时间:2015-03-06 19:02:53

标签: python python-3.x tuples 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

将不存在的值设置为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 onethis one有些相反。)

1 个答案:

答案 0 :(得分:11)

您可以使用以下内容添加其余元素:

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)