扩展元组在Python 2中解压缩
问题描述:
是否可以在Python 2中模拟扩展元组解压缩?扩展元组在Python 2中解压缩
具体来说,我有一个循环:
for a, b, c in mylist:
时MYLIST是大小为3的元组的列表,它工作正常。如果我通过一个大小为4的列表,我想让循环工作。
我想我会最终使用命名元组,但我想知道如果有一个简单的方法来写:
for a, b, c, *d in mylist:
使d
吃掉任何额外的成员。
答
您可以定义一个包装函数,将列表转换为四元组。例如:
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,)
答
对于它的赫克,广义解压任意数量的元素:
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
答
你不能直接这样做,但编写实用程序功能并不难:
>>> 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)
http://stackoverflow.com/questions/10299682/how-to-unpack-tuple-of-length-n-to-mn-variables一般 – n611x007 2014-12-12 15:19:41
http://stackoverflow.com/questions/7028435/how-to-separate-output-data special – n611x007 2014-12-12 15:20:54
https://stackoverflow.com/questions/20501440/idiomatic-way-to-unpack-variable-length-list特殊 – n611x007 2014-12-12 15:50:54