Extended tuple unpacking in Python 2

前端 未结 5 1283
时光取名叫无心
时光取名叫无心 2020-11-27 21:14

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

Specifically, I have a for loop:

for a, b, c in mylist:

which work

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 21:39

    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
    

    The code prints:

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

提交回复
热议问题