python merge two lists (even/odd elements)

后端 未结 7 1410
旧时难觅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:43

    It can be done with slicing. Do count and slice in terminal:

    >>> list1=['Apple','Mango','Orange']
    >>> list2=['One','Two','Three']
    >>> list = [None]*(len(list1)+len(list2))
    >>> list[::2] = list1
    >>> list[1::2] = list2
    >>> list
    

    Output:

     ['Apple', 'One', 'Mango', 'Two', 'Orange', 'Three']
    

提交回复
热议问题