python merge two lists (even/odd elements)

后端 未结 7 1328
旧时难觅i
旧时难觅i 2021-01-19 16:16

Given two lists, I want to merge them so that all elements from the first list are even-indexed (preserving their order) and all elements from second list are odd-indexed (a

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-19 16:48

    You can simply do:

    for i,v in enumerate(y):
        x.insert(2*i+1,v)
    

    this takes the advantage that insert will use the last index when it is overpassed.

    One example:

    x = [0,1,2,3,4,5]
    y = [100, 11,22,33,44,55,66,77]
    print x
    # [0, 100, 1, 11, 2, 22, 3, 33, 4, 44, 5, 55, 66, 77]
    

提交回复
热议问题