Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3075
误落风尘
误落风尘 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 16:55

    Here's one way to do it by slicing:

    >>> list1 = ['f', 'o', 'o']
    >>> list2 = ['hello', 'world']
    >>> result = [None]*(len(list1)+len(list2))
    >>> result[::2] = list1
    >>> result[1::2] = list2
    >>> result
    ['f', 'hello', 'o', 'world', 'o']
    

提交回复
热议问题