简体   繁体   中英

Merge two vectors with alternate locations

I have:

import numpy as np
A = np.asarray([1,3,5,7,9])
B = np.asarray([2,4,6,8,10])

I want to create:

C = np.asarray([1,2,3, 4,5,6,7,8,9,10])

Is there a better way to do than to run a for loop

You can the stack arrays vertically using vstack , transpose and then ravel :

>>> A = np.asarray([1,3,5,7,9])
>>> B = np.asarray([2,4,6,8,10])
>>> C = np.vstack((A, B)).T.ravel()
>>> C
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Try the following :

import numpy as np
A = np.asarray([1,3,5,7,9])
B = np.asarray([2,4,6,8,10])

C = np.sort(np.hstack((A,B)))
#array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM