Python array initialization

I want to initialize an array with 10 values, starting with X and incrementing by Y. I cannot directly use range() , since this requires a maximum value, not the number of values.

I can do this in a loop as shown below:

 a = [] v = X for i in range(10): a.append(v) v = v + Y 

But I'm sure it needs a cute python single liner ...

+6
source share
5 answers
 >>> x = 2 >>> y = 3 >>> [i*y + x for i in range(10)] [2, 5, 8, 11, 14, 17, 20, 23, 26, 29] 
+14
source

You can use this:

 >>> x = 3 >>> y = 4 >>> range(x, x+10*y, y) [3, 7, 11, 15, 19, 23, 27, 31, 35, 39] 
+8
source

Another way to do it

 Y=6 X=10 N=10 [y for x,y in zip(range(0,N),itertools.count(X,Y))] [10, 16, 22, 28, 34, 40, 46, 52, 58, 64] 

And one more way

 map(lambda (x,y):y,zip(range(0,N),itertools.count(10,Y))) [10, 16, 22, 28, 34, 40, 46, 52, 58, 64] 

And one more way

 import numpy numpy.array(range(0,N))*Y+X array([10, 16, 22, 28, 34, 40, 46, 52, 58, 64]) 

And even that

 C=itertools.count(10,Y) [C.next() for i in xrange(10)] [10, 16, 22, 28, 34, 40, 46, 52, 58, 64] 
+2
source
 [x+i*y for i in xrange(1,10)] 

will complete the task

+2
source

If I understand your question correctly:

 Y = 6 a = [x + Y for x in range(10)] 

Edit: Oh, I see, I misunderstood the question. Go on.

+1
source

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


All Articles