Pythonic way to combine two lists in an alternating fashion?

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

    I know the questions asks about two lists with one having one item more than the other, but I figured I would put this for others who may find this question.

    Here is Duncan's solution adapted to work with two lists of different sizes.

    list1 = ['f', 'o', 'o', 'b', 'a', 'r']
    list2 = ['hello', 'world']
    num = min(len(list1), len(list2))
    result = [None]*(num*2)
    result[::2] = list1[:num]
    result[1::2] = list2[:num]
    result.extend(list1[num:])
    result.extend(list2[num:])
    result
    

    This outputs:

    ['f', 'hello', 'o', 'world', 'o', 'b', 'a', 'r'] 
    

提交回复
热议问题