split list into 2 lists corresponding to every other element

后端 未结 3 1171
广开言路
广开言路 2021-01-12 03:23

I know there are many chunky ways to do this, but I am looking for a slick pythonic way to accomplish the following. Given a list of numbers:

a = [0,1,2,3,4,         


        
3条回答
  •  旧巷少年郎
    2021-01-12 03:43

    You can do that using list slicing:

    b = a[::2]
    c = a[1::2]
    

    Example

    >>> a = [0,1,2,3,4,5,6,7,8,9]
    
    >>> b = a[::2]
    >>> c = a[1::2]
    
    >>> print b
    [0,2,4,6,8]
    
    >>> print c
    [1,3,5,7,9]
    

    The [::] syntax is as follows: [start:end:step]. If you don't specify any parameters for start and end, it will work with the whole list. Therefore, what the code above is doing is:

    For b: start at index 0, take every other element from a
    For c: start at index 1, take every other element from a

提交回复
热议问题