python merge two lists (even/odd elements)

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

    This is simple enough although not nearly as flexible as roundrobin:

    def paired(it1, it2):
        it2 = iter(it2)
        for item in it1:
            yield item
            yield next(it2)
    

    tested in 2.7.5:

    >>> x = [0, 1, 2]
    >>> y = [3, 4]
    >>> print list(paired(x, y))
    [0, 3, 1, 4, 2]
    

    Note that it stops as soon as the list y runs out (because next(it2) raises StopIteration).

提交回复
热议问题