【问题标题】:How to unpack a tuple into more values than the tuple has?如何将元组解压缩成比元组更多的值?
【发布时间】:2015-05-08 11:21:40
【问题描述】:

我有一个元组列表,每个元组包含 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或this one有些相反。)

【问题讨论】:

    标签: python python-3.x tuples iterable-unpacking


    【解决方案1】:

    你可以添加剩余的元素:

    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)
    

    【讨论】:

    • t = (1, 2) a, b, c, d, e, *_ = *t, *((None,) * 5) 也可以使用
    猜你喜欢
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2014-08-26
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    相关资源
    最近更新 更多