Extended tuple unpacking in Python 2

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

    Python 3 solution for those that landed here via an web search:

    You can use itertools.zip_longest, like this:

    from itertools import zip_longest
    
    max_params = 4
    
    lst = [1, 2, 3, 4]
    a, b, c, d = next(zip(*zip_longest(lst, range(max_params))))
    print(f'{a}, {b}, {c}, {d}') # 1, 2, 3, 4
    
    lst = [1, 2, 3]
    a, b, c, d = next(zip(*zip_longest(lst, range(max_params))))
    print(f'{a}, {b}, {c}, {d}') # 1, 2, 3, None
    

    For Python 2.x you can follow this answer.

提交回复
热议问题