Extended tuple unpacking in Python 2

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

    You can write a very basic function that has exactly the same functionality as the python3 extended unpack. Slightly verbose for legibility. Note that 'rest' is the position of where the asterisk would be (starting with first position 1, not 0)

    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)
    

提交回复
热议问题