Python: easy way to increment using variable values?

I am creating a list of integers that should increase by 2 variable values.

For example, starting from 0 and alternating between 4 and 2 to 20, do:

[0,4,6,10,12,16,18]

range and xrange accept only one integer for the increment value. What is the easiest way to do this?

+4
source share
5 answers

I could use simple itertools.cycleto complete the following steps:

from itertools import cycle
def fancy_range(start, stop, steps=(1,)):
    steps = cycle(steps)
    val = start
    while val < stop:
        yield val
        val += next(steps)

You would call it that:

>>> list(fancy_range(0, 20, (4, 2)))
[0, 4, 6, 10, 12, 16, 18]

The advantage here is that scaling to an arbitrary number of steps is pretty good (although I can't think of good use for this at the moment - but maybe you can).

+12
source

, . :

>>> [3*i + i%2 for i in range(10)]
[0, 4, 6, 10, 12, 16, 18, 22, 24, 28]
+6
l = []
a = 0
for i in xrnage (N) :
    a += 2
    if i&1 == 0 :
        a+=2
    l.append (a)

.

+1

.

def custom_range(first, second, range_limit):
    start , end = range_limit
    step = first + second
    a = range(start, end, step)
    b = range(first, end, step)
    from itertools import izip_longest
    print [j for i in izip_longest(a,b) for j in i if j!=None]

custom_range(4,2,(0,19))
custom_range(6,5,(0,34))

:

[0, 4, 6, 10, 12, 16, 18]
[0, 6, 11, 17, 22, 28, 33]
0

1 Create a range of numbers from 0 to n in steps of 4 2 generate another range of numbers from 0 to n in steps of 6 3 Combine the list and sort. Remove duplicates

>>> a = range(0,20,4)
>>> a
[0, 4, 8, 12, 16]
>>> b = range(0,20,6)
>>> c = sorted(a + b)
>>> b
[0, 6, 12, 18]
>>> c
[0, 0, 4, 6, 8, 12, 12, 16, 18]
>>> c = list(set(c))
>>> c
[0, 4, 6, 8, 12, 16, 18]
0
source

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


All Articles