Skip first entry in for loop in python?

前端 未结 13 2424
面向向阳花
面向向阳花 2020-12-02 05:15

In python, How do I do something like:

for car in cars:
   # Skip first and last, do work for rest
相关标签:
13条回答
  • 2020-12-02 06:05

    An alternative method:

    for idx, car in enumerate(cars):
        # Skip first line.
        if not idx:
            continue
        # Skip last line.
        if idx + 1 == len(cars):
            continue
        # Real code here.
        print car
    
    0 讨论(0)
  • 2020-12-02 06:07

    Example:

    mylist=['one'.'two','three'.'four'.'five']
    for i in mylist[1:]:
       print(i)
    

    In python index start from 0, We can use slicing operator to make manipulations in iteration.

    for i in range(1,-1):
    
    0 讨论(0)
  • 2020-12-02 06:11

    To skip the first element in Python you can simply write

    for car in cars[1:]:
        # Do What Ever you want
    

    or to skip the last elem

    for car in cars[:-1]:
        # Do What Ever you want
    

    You can use this concept for any sequence.

    0 讨论(0)
  • 2020-12-02 06:12

    If cars is a sequence you can just do

    for car in cars[1:-1]:
        pass
    
    0 讨论(0)
  • 2020-12-02 06:15

    Here is a more general generator function that skips any number of items from the beginning and end of an iterable:

    def skip(iterable, at_start=0, at_end=0):
        it = iter(iterable)
        for x in itertools.islice(it, at_start):
            pass
        queue = collections.deque(itertools.islice(it, at_end))
        for x in it:
            queue.append(x)
            yield queue.popleft()
    

    Example usage:

    >>> list(skip(range(10), at_start=2, at_end=2))
    [2, 3, 4, 5, 6, 7]
    
    0 讨论(0)
  • 2020-12-02 06:15

    The more_itertools project extends itertools.islice to handle negative indices.

    Example

    import more_itertools as mit
    
    iterable = 'ABCDEFGH'
    list(mit.islice_extended(iterable, 1, -1))
    # Out: ['B', 'C', 'D', 'E', 'F', 'G']
    

    Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:

    for car in mit.islice_extended(cars, 1, -1):
        # do something
    
    0 讨论(0)
提交回复
热议问题