Skipping every other element after the first

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

    Or you can do it like this!

        def skip_elements(elements):
            # Initialize variables
            new_list = []
            i = 0
    
            # Iterate through the list
            for words in elements:
    
                # Does this element belong in the resulting list?
                if i <= len(elements):
                    # Add this element to the resulting list
                    new_list.append(elements[i])
                # Increment i
                    i += 2
    
            return new_list
    
        print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
        print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
        print(skip_elements([])) # Should be []
    
    
    0 讨论(0)
  • 2020-12-04 21:43
    items = range(10)
    print items
    >>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    print items[1::2] # every other item after the second; slight variation
    >>> [1, 3, 5, 7, 9]
    ]
    
    0 讨论(0)
  • 2020-12-04 21:44

    Slice notation a[start_index:end_index:step]

    return a[::2]
    

    where start_index defaults to 0 and end_index defaults to the len(a).

    0 讨论(0)
  • 2020-12-04 21:47
    def skip_elements(elements):
        # Initialize variables
        new_list = []
        i = 0
    
        # Iterate through the list
        for words in elements:
            # Does this element belong in the resulting list?
            if i <= len(elements):
                # Add this element to the resulting list
                new_list.insert(i,elements[i])
            # Increment i
            i += 2
    
        return new_list
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-04 21:53
    b = a[::2]
    

    This uses the extended slice syntax.

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