Python 2中的扩展元组解包

时间:2011-03-17 01:05:06

标签: python tuples iterable-unpacking

是否可以在Python 2中模拟扩展元组解包?

具体来说,我有一个for循环:

for a, b, c in mylist:

当mylist是大小为3的元组列表时工作正常。如果我传入一个大小为四的列表,我希望循环工作相同。

我想我最终会使用命名元组,但我想知道是否有一种简单的写法:

for a, b, c, *d in mylist:

以便d吃掉任何额外的成员。

5 个答案:

答案 0 :(得分:22)

你不能直接这样做,但是编写实用程序函数来执行此操作并不是非常困难:

>>> def unpack_list(a, b, c, *d):
...   return a, b, c, d
... 
>>> unpack_list(*range(100))
(0, 1, 2, (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99))

你可以将它应用到你的for循环中:

for sub_list in mylist:
    a, b, c, d = unpack_list(*sub_list)

答案 1 :(得分:14)

您可以定义一个包装函数,将列表转换为四元组。例如:

def wrapper(thelist):
    for item in thelist:
        yield(item[0], item[1], item[2], item[3:])

mylist = [(1,2,3,4), (5,6,7,8)]

for a, b, c, d in wrapper(mylist):
    print a, b, c, d

代码打印:

1 2 3 (4,)
5 6 7 (8,)

答案 2 :(得分:10)

对于它来说,通常化解包任意数量的元素:

lst = [(1, 2, 3, 4, 5), (6, 7, 8), (9, 10, 11, 12)]

def unpack(seq, n=2):
    for row in seq:
        yield [e for e in row[:n]] + [row[n:]]

for a, rest in unpack(lst, 1):
    pass

for a, b, rest in unpack(lst, 2):
    pass

for a, b, c, rest in unpack(lst, 3):
    pass

答案 3 :(得分:0)

您可以编写一个非常基本的功能,该功能与python3扩展解压缩功能完全相同。略显易读。请注意,“ rest”是星号所在的位置(从第一个位置1开始,而不是0)

def extended_unpack(seq, n=3, rest=3):
    res = []; cur = 0
    lrest = len(seq) - (n - 1)    # length of 'rest' of sequence
    while (cur < len(seq)):
        if (cur != rest):         # if I am not where I should leave the rest
            res.append(seq[cur])  # append current element to result
        else:                     # if I need to leave the rest
            res.append(seq[cur : lrest + cur]) # leave the rest
            cur = cur + lrest - 1 # current index movded to include rest
        cur = cur + 1             # update current position
     return(res)

答案 4 :(得分:0)

针对那些通过网络搜索登陆的Python 3解决方案:

您可以使用itertools.zip_longest,如下所示:

from itertools import zip_longest

max_params = 4

lst = [1, 2, 3, 4]
a, b, c, d = next(zip(*zip_longest(lst, range(max_params))))
print(f'{a}, {b}, {c}, {d}') # 1, 2, 3, 4

lst = [1, 2, 3]
a, b, c, d = next(zip(*zip_longest(lst, range(max_params))))
print(f'{a}, {b}, {c}, {d}') # 1, 2, 3, None

对于Python 2.x,您可以遵循此answer