python merge two lists (even/odd elements)

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

    Use the roundrobin recipe from itertools:

    from itertools import cycle, islice
    def roundrobin(*iterables):
        "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
        # Recipe credited to George Sakkis
        pending = len(iterables)
        nexts = cycle(iter(it).next for it in iterables)
        while pending:
            try:
                for next in nexts:
                    yield next()
            except StopIteration:
                pending -= 1
                nexts = cycle(islice(nexts, pending))
    >>> list(roundrobin(x,y))
    [0, 3, 1, 4, 2]
    

提交回复
热议问题