Skipping every other element after the first

后端 未结 13 2169
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2020-12-04 21:54
    def skip_elements(elements):
       new_list = [ ]
       i = 0
       for element in elements:
           if i%2==0:
             c=elements[i]
             new_list.append(c)
           i+=1
      return new_list
    
    0 讨论(0)
  • 2020-12-04 21:55
    def altElement(a):
        return a[::2]
    
    0 讨论(0)
  • 2020-12-04 21:55

    Using the for-loop like you have, one way is this:

    def altElement(a):
        b = []
        j = False
        for i in a:
            j = not j
            if j:
                b.append(i)
    
        print b
    

    j just keeps switching between 0 and 1 to keep track of when to append an element to b.

    0 讨论(0)
  • 2020-12-04 21:55
    def skip_elements(elements):
        # Initialize variables
        i = 0
        new_list=elements[::2]
        return new_list
    
    # Should be ['a', 'c', 'e', 'g']:    
    print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
    # Should be ['Orange', 'Strawberry', 'Peach']:
    print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) 
    # Should be []:
    print(skip_elements([]))
    
    0 讨论(0)
  • 2020-12-04 22:00

    Alternatively, you could do:

    for i in range(0, len(a), 2):
        #do something
    

    The extended slice notation is much more concise, though.

    0 讨论(0)
提交回复
热议问题