python merge two lists (even/odd elements)

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

    Here's something you can use. (Use list(izip_longest(...)) for Py2x)

    >>> from itertools import chain
    >>> from itertools import zip_longest
    >>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = ''))))
    [0, 3, 1, 4, 2]
    

    This works for arbitrary length lists like follows -

    >>> x = [0, 1, 2, 3, 4]
    >>> y = [5, 6]
    >>> list(filter(lambda x: x != '', chain.from_iterable(zip_longest(x, y, fillvalue = ''))))
    [0, 5, 1, 6, 2, 3, 4]
    

    Explanation on it's working -

    1. zip_longest(...) with a fill value zips the lists and fills in the given fill value for iterables of unequal length. So, for your original example, it evaluates to something like [(0, 3), (1, 4), (2, '')]
    2. We need to flatten the result because this method gives us a list of tuples. For that we use chain.from_iterable(...) giving us something like [0, 3, 1, 4, 2, ''].
    3. We now use filter(...) to remove all occurences of '' and we get the required answer.

提交回复
热议问题