Python 2 中的扩展元组解包 [英] Extended tuple unpacking in Python 2

查看:44
本文介绍了Python 2 中的扩展元组解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to simulate extended tuple unpacking in Python 2?

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

Specifically, I have a for loop:

for a, b, c in mylist:

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

which works fine when mylist is a list of tuples of size three. I want the same for loop to work if I pass in a list of size four.

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

I think I will end up using named tuples, but I was wondering if there is an easy way to write:

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

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

so that d eats up any extra members.

推荐答案

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

You could define a wrapper function that converts your list to a four tuple. For example:

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,)

这篇关于Python 2 中的扩展元组解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆