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

后端 未结 4 1585
日久生厌
日久生厌 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 10:43

    I just wanted to clear something. Say you have a list

    list1 = list(range(200))
    

    you can do either :

    ## OPTION A ##
    a = list1[1::2]
    b = list1[0::2]
    

    or

    ## OPTION B ##
    a = list1[0:][::2] # even
    b = list1[1:][::2] # odd
    

    And get have alternative elements in variable a and b.

    But OPTION A is twice as fast

提交回复
热议问题