python merge two lists (even/odd elements)

后端 未结 7 1322
旧时难觅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条回答
  •  心在旅途
    2021-01-19 16:55

    Try this:

    x = [0,1,2,10,11]
    y = [3,4]
    
    n =  2*max([len(x),len(y)])
    res = n *[None]
    res[:2*len(x):2] = x
    res[1:2*len(y):2] = y
    res = [x for x in res if x!=None]
    print res
    

    It should work for unevenly long lists.

提交回复
热议问题