Python 2中的扩展元组解包

问题描述 投票:28回答:4

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

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

for a, b, c in mylist:

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

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

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

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

python tuples iterable-unpacking
4个回答
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,)

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)

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.