Extended tuple unpacking in Python 2

前端 未结 5 1280
时光取名叫无心
时光取名叫无心 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:27

    For the heck of it, generalized to unpack any number of elements:

    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
    

提交回复
热议问题