Skipping every other element after the first

后端 未结 13 2170
深忆病人
深忆病人 2020-12-04 21:13

I have the general idea of how to do this in Java, but I am learning Python and not sure how to do it.

I need to implement a function that returns a list containing

13条回答
  •  情深已故
    2020-12-04 21:52

    There are more ways than one to skin a cat. - Seba Smith

    arr = list(range(10)) # Range from 0-9
    
    # List comprehension: Range with conditional
    print [arr[index] for index in range(len(arr)) if index % 2 == 0]
    
    # List comprehension: Range with step
    print [arr[index] for index in range(0, len(arr), 2)]
    
    # List comprehension: Enumerate with conditional
    print [item for index, item in enumerate(arr) if index % 2 == 0]
    
    # List filter: Index in range
    print filter(lambda index: index % 2 == 0, range(len(arr)))
    
    # Extended slice
    print arr[::2]
    

提交回复
热议问题