Pythonic way to combine two lists in an alternating fashion?

前端 未结 21 3294
误落风尘
误落风尘 2020-11-22 16:13

I have two lists, the first of which is guaranteed to contain exactly one more item than the second. I would like to know the most Pythonic way to create a

21条回答
  •  臣服心动
    2020-11-22 16:55

    Stops on the shortest:

    def interlace(*iters, next = next) -> collections.Iterable:
        """
        interlace(i1, i2, ..., in) -> (
            i1-0, i2-0, ..., in-0,
            i1-1, i2-1, ..., in-1,
            .
            .
            .
            i1-n, i2-n, ..., in-n,
        )
        """
        return map(next, cycle([iter(x) for x in iters]))
    

    Sure, resolving the next/__next__ method may be faster.

提交回复
热议问题