Issue
For some code I'm writing, I need to iterate from 1-30 skipping 6. What I tried naively is
a = range(1,6)
b = range(7,31)
for i in a+b:
print i
Is there a way to do it more efficiently?
Solution
In python 2 you are not combining "range functions"; these are just lists. Your example works just well. But range always creates a full list in memory, so a better way if only needed in for loop could be to to use a generator expression and xrange:
range_with_holes = (j for j in xrange(1, 31) if j != 6)
for i in range_with_holes:
....
In generator expression the if part can contain a complex logic on which numbers to skip.
Another way to combine iterables is to use the itertools.chain
:
range_with_holes = itertools.chain(xrange(1, 6), xrange(7, 31))
Or just skip the unwanted index
for i in range(1, 31):
if i == 6:
continue
...
Answered By - Antti Haapala -- Слава Україні
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.