Python 2中扩展的元组解压缩

Extended tuple unpacking in Python 2

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

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

1
for a, b, c in mylist:

当mylist是大小为3的元组的列表时,它可以正常工作。 如果我传入大小为4的列表,我希望相同的for循环能够正常工作。

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

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

这样d会吞噬所有多余的成员。


您不能直接做到这一点,但是编写一个实用程序函数来做到这一点并不困难:

1
2
3
4
5
>>> 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循环,如下所示:

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

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

1
2
3
4
5
6
7
8
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
1 2 3 (4,)
5 6 7 (8,)


对于此问题,可以概括为解压缩任意数量的元素:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

适用于通过网络搜索登陆的Python 3解决方案:

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

1
2
3
4
5
6
7
8
9
10
11
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,您可以遵循以下答案。


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

1
2
3
4
5
6
7
8
9
10
11
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)