I want to map a list or array into an array in python 3.x
, input a [a,b,c]
and get result like [a*2, a*2+1, b*2, b*2+1, c*2, c*2+1]
e.g:
a = np.array([2,4,6])
result = []
for a1,a2 in zip(a*2, a*2+1):
result = result + [a1,a2]
print(result)
# Output: [4, 5, 8, 9, 12, 13]
There must be better ways. Both list and numpy
solutions will be ok. Thanks
One way to do that:
import numpy as np
a = np.array([2, 4, 6])
b = np.repeat(2 * a, 2)
b[1::2] += 1
print(b)
# [ 4 5 8 9 12 13]
Another way:
b = np.stack([2 * a, 2 * a + 1], axis=1).ravel()
EDIT:
If you want a solution that allows you to enlarge the array by any factor, not just 2, you can use a function like this:
import numpy as np
def make_longer(a, n):
b = np.tile(n * a[:, np.newaxis], (1, n))
b += np.arange(n, dtype=b.dtype)
return b.ravel()
a = np.array([2, 4, 6])
print(make_longer(a, 2))
# [ 4 5 8 9 12 13]
print(make_longer(a, 3))
# [ 6 7 8 12 13 14 18 19 20]
You can try;
In [1]: a = [2, 4, 6]
In [2]: f1 = lambda x: x*2
In [3]: f2 = lambda x:x*2+1
In [4]: [f(x) for x in a for f in (f1, f2)]
Out[4]: [4, 5, 8, 9, 12, 13]
or for one liner
In [4]: [f(i) for i in a for f in (lambda x: x*2, lambda x: x*2+1)]
Out[4]: [4, 5, 8, 9, 12, 13]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With