Python program to split a list into two lists with alternating elements

后端 未结 4 1588
日久生厌
日久生厌 2020-11-29 10:37

Can you make it more simple/elegant?

def zigzag(seq):
    \"\"\"Return two sequences with alternating elements from `seq`\"\"\"
    x, y = [], []
    p, q =          


        
4条回答
  •  时光说笑
    2020-11-29 11:04

    This takes an iterator and returns two iterators:

    import itertools
    def zigzag(seq):
        t1,t2 = itertools.tee(seq)
        even = itertools.islice(t1,0,None,2)
        odd = itertools.islice(t2,1,None,2)
        return even,odd
    

    If you prefer lists then you can return list(even),list(odd).

提交回复
热议问题