Echan
Echan

Reputation: 1415

Map python array into a x times longer array using each element x times

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

Upvotes: 5

Views: 100

Answers (4)

Lin GU
Lin GU

Reputation: 89

It's just one line code in python.

Solution 1 :

[x for i in a for x in (2*i, 2*i + 1)]

Solution 2 (map):

[rv for r in zip(list(map(lambda x: 2 * x, a)), list(map(lambda x: 2 * x + 1, a))) for rv in r]

Input:

>>> a = [2, 4, 6]

Output:

[4, 5, 8, 9, 12, 13]

Upvotes: 1

kantal
kantal

Reputation: 2407

The very simple way:

l=[2,4,6]
r=[]                                                                                                                 
for i in l: 
   r.extend([2*i,2*i+1])

print(r)                                                                                                                
[4, 5, 8, 9, 12, 13]

Or:

g=lambda i: (2*i,2*i+1)                                                                                              
[ e for i in l for e in g(i) ]                                                                                       
Out: [4, 5, 8, 9, 12, 13]

Upvotes: 0

javidcf
javidcf

Reputation: 59701

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]

Upvotes: 4

Praveen
Praveen

Reputation: 9345

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]

Upvotes: 2

Related Questions