In python, How do I do something like:
for car in cars:
# Skip first and last, do work for rest
![How to skip the first element in a dictionary when using a for loop to iterate through the dictionary? [duplicate]](https://file.115kc.com/storage/eg/image298.jpg)
0 Answer
I do it like this, even though it looks like a hack it works every time:
ls_of_things = ['apple', 'car', 'truck', 'bike', 'banana']
first = 0
last = len(ls_of_things)
for items in ls_of_things:
if first == 0
first = first + 1
pass
elif first == last - 1:
break
else:
do_stuff
first = first + 1
pass
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
Similar to @maninthecomputer 's answer, when you need to skip the first iteration of a loop based on an int (self._model.columnCount()
in my case):
for col in range(self._model.columnCount()):
if col == 0:
continue
Put more simply:
test_int = 3
for col in range(test_int):
if col == 0:
continue
print(col)
Provides output:
1
2
3
Good solution for support of itertools.chain
is to use itertools.islice
in order to take a slice of an iterable:
your_input_list = ['list', 'of', 'things']
for i, variant in list(itertools.islice(enumerate(some_function_that_will_output_itertools_chain(your_input_list)), 1, None)):
"""
# No need for unnecessary conditions like this:
if i == 0:
continue
"""
variant = list(variant) # (optional) converting back to list
print(variant)
Well, your syntax isn't really Python to begin with.
Iterations in Python are over he contents of containers (well, technically it's over iterators), with a syntax for item in container
. In this case, the container is the cars
list, but you want to skip the first and last elements, so that means cars[1:-1]
(python lists are zero-based, negative numbers count from the end, and :
is slicing syntax.
So you want
for c in cars[1:-1]:
do something with c
Based on @SvenMarnach 's Answer, but bit simpler and without using deque
>>> def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
it = itertools.islice(it, at_start, None)
it, it1 = itertools.tee(it)
it1 = itertools.islice(it1, at_end, None)
return (next(it) for _ in it1)
>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]
Also Note, based on my timeit
result, this is marginally faster than the deque solution
>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
it = iter(iterable)
it = itertools.islice(it, at_start, None)
it, it1 = itertools.tee(it)
it1 = itertools.islice(it1, at_end, None)
return (next(it) for _ in it1)
list(skip(iterable,2,2))
"""
>>> stmt2="""
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()
list(skip(iterable,2,2))
"""
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716
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
This code skips the first and the last element of the list:
for item in list_name[1:-1]:
#...do whatever
Here's my preferred choice. It doesn't require adding on much to the loop, and uses nothing but built in tools.
Go from:
for item in my_items:
do_something(item)
to:
for i, item in enumerate(my_items):
if i == 0:
continue
do_something(item)
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):
这家伙很懒,什么都没留下...