Skipping every other element after the first

后端 未结 13 2173
深忆病人
深忆病人 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:53

    def skip_elements(elements):
      new_list = []
      for index,element in enumerate(elements):
        if index == 0:
          new_list.append(element)
        elif (index % 2) == 0: 
          new_list.append(element)
      return new_list
    

    Also can use for loop + enumerate. elif (index % 2) == 0: ## Checking if number is even, not odd cause indexing starts from zero not 1.

提交回复
热议问题