5

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

1
  • 1
    np.add.outer(2*a, np.arange(2)).ravel()? Commented Nov 29, 2018 at 13:51

4 Answers 4

4

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]
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

1

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]

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.