How to combine range () functions

For some code that I write, I need to iterate from 1 to 30 passes. 6. I naively naively tried

a = range(1,6) b = range(7,31) for i in a+b: print i 

Is there a way to do this more efficiently?

+6
source share
3 answers

In python 2 you do not combine "range functions"; these are just lists. Your example works well. But a range always creates a complete list in memory, so the best way, if only needed for a loop, is 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 the generator expression, the if part may contain complex logic by which the missing numbers.

Another way to combine iterations is to use 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 ... 
+10
source

Use itertools.chain :

 import itertools a = range(1,6) b = range(7,31) for i in itertools.chain(a, b): print i 

Or complex generator smoothing expressions:

 a = range(1,6) b = range(7,31) for i in (x for y in (a, b) for x in y): print i 

Or skip in the generator expression:

 skips = set((6,)) for i in (x for x in range(1, 31) if x not in skips): print i 

Any of these will work for any iteration, not just range in Python 3 or lists in Python 2.

+10
source

One option is to use the skip list and check for this, for example:

 skips = [6, 42] for i in range(1,31): if i in skips: continue print i 
+2
source

Source: https://habr.com/ru/post/952043/


All Articles