Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3274
误落风尘
误落风尘 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:06

    Without itertools and assuming l1 is 1 item longer than l2:

    >>> sum(zip(l1, l2+[0]), ())[:-1]
    ('f', 'hello', 'o', 'world', 'o')
    

    Using itertools and assuming that lists don't contain None:

    >>> filter(None, sum(itertools.izip_longest(l1, l2), ()))
    ('f', 'hello', 'o', 'world', 'o')
    

提交回复
热议问题