Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3365
误落风尘
误落风尘 2020-11-22 16:13

I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a

21条回答
  •  情书的邮戳
    2020-11-22 17:11

    Multiple one-liners inspired by answers to another question:

    import itertools
    
    list(itertools.chain.from_iterable(itertools.izip_longest(list1, list2, fillvalue=object)))[:-1]
    
    [i for l in itertools.izip_longest(list1, list2, fillvalue=object) for i in l if i is not object]
    
    [item for sublist in map(None, list1, list2) for item in sublist][:-1]
    

提交回复
热议问题