0
len_array = 10
A = np.zeros( len_array )
B = np.zeros( len_array )

A = np.arange(1, 5, 0.5)
B = np.arange(11, 15, 0.5)
A = A.tolist()
B = B.tolist()

I followed another post that did similar task, however it just insert elements in B into A. This method did not generate a new list C.

for i,v in enumerate(B):
    A.insert(2*i+1,v) 

How to create a new list C that merges A and B based on their even/odd elements?

Thanks.

Kuo-Hsien Chang
  • 925
  • 17
  • 40
  • 1
    Can you show your expected output? You're calling `tolist`, but is your intent to work with numpy arrays or Python lists? I don't understand what the initial calls to `np.zeros` do since these variables are overwritten by `arange` later. – ggorlen Jun 17 '20 at 01:02
  • even/odd by index or value? Give a full working example. – hpaulj Jun 17 '20 at 01:08
  • Is one of your list even and the other with odd elements? Or are both of the lists with random odd and even elements? – DirtyBit Jun 17 '20 at 01:08
  • 1
    if I understand correctly, see roundrobin in https://docs.python.org/2/library/itertools.html#recipes or https://stackoverflow.com/questions/2017895/alternating-between-iterators-in-python (put it in a list comprehension to get a list) – Kenny Ostrom Jun 17 '20 at 01:33
  • Of course, if you have working code, but you want it in a new list C instead of A, then just do the same thing after C = A.copy() Not the most efficient, but if you want a new list C instead of A ... just do it. – Kenny Ostrom Jun 17 '20 at 01:39

5 Answers5

2
In [194]: A = np.arange(1, 5, 0.5) 
     ...: B = np.arange(11, 15, 0.5)                                                                            

The list derived from A is a copy. in-place changes to C don't affect A:

In [196]: C = A.tolist()                                                                                        
In [197]: for i,v in enumerate(B): 
     ...:     C.insert(2*i+1,v) 
     ...:                                                                                                       
In [198]: A                                                                                                     
Out[198]: array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
In [199]: B                                                                                                     
Out[199]: array([11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5])
In [200]: C                                                                                                     
Out[200]: 
[1.0,
 11.0,
 1.5,
 11.5,
 2.0,
 12.0,
 2.5,
 12.5,
 3.0,
 13.0,
 3.5,
 13.5,
 4.0,
 14.0,
 4.5,
 14.5]

An array approach:

In [201]: np.vstack((A,B))                                                                                      
Out[201]: 
array([[ 1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5],
       [11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5]])
In [202]: np.vstack((A,B)).ravel(order='F')                                                                     
Out[202]: 
array([ 1. , 11. ,  1.5, 11.5,  2. , 12. ,  2.5, 12.5,  3. , 13. ,  3.5,
       13.5,  4. , 14. ,  4.5, 14.5])

Or we could stack the arrays as columns and do the ordinary C order ravel.

===

Another list way - use zip to make list of lists, and itertools.chain to flatten that:

In [203]: import itertools                                                                                      
In [204]: [(i,j) for i,j in zip(A,B)]                                                                           
Out[204]: 
[(1.0, 11.0),
 (1.5, 11.5),
 (2.0, 12.0),
 (2.5, 12.5),
 (3.0, 13.0),
 (3.5, 13.5),
 (4.0, 14.0),
 (4.5, 14.5)]
In [205]: list(itertools.chain(*[(i,j) for i,j in zip(A,B)]))                                                   
Out[205]: 
[1.0,
 11.0,
 1.5,
 11.5,
 2.0,
 12.0,
 2.5,
 12.5,
 3.0,
 13.0,
 3.5,
 13.5,
 4.0,
 14.0,
 4.5,
 14.5]
hpaulj
  • 221,503
  • 14
  • 230
  • 353
1

I recommend using numpy instead of converting them to lists (i.e. before A = A.tolist() and B = B.tolist()):

C = np.dstack((A,B)).flatten()

But if you insist on using lists, you can create a list and add insert lists to it:

C = [None]*(len(A)+len(B))
C[::2] = A
C[1::2] = B

They both create a similar outputs (one numpy array and the other list). The output in your example:

[1.0, 11.0, 1.5, 11.5, 2.0, 12.0, 2.5, 12.5, 3.0, 13.0, 3.5, 13.5, 4.0, 14.0, 4.5, 14.5]
Ehsan
  • 12,072
  • 2
  • 20
  • 33
  • I like the use on np, but the other solution will fail is the lists are of different length. – Johan Schiff Jun 17 '20 at 01:47
  • @JohanSchiff Agreed. But judging by the for loop provided by OP in question, I assumed this is the case that `A` and `B` are of same length. Otherwise, merging odd/even is questionable and needs to be clarified. – Ehsan Jun 17 '20 at 01:52
0

Using a combination of builtin zip() and list comprehensions.

C = [item for sublist in zip(A, B) for item in sublist]

Here's what this code (sort of) does in a more verbose way:

C = []
for sublist in zip(A, B):
    for item in sublist:
         C.append(item)

Or a bit shorter:

C = []
for sublist in zip(A, B):
    C.extend(sublist)

Note that using zip(A, B) will stop when the shortest list ends. If you need a different behaviour, use zip_longest().

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Johan Schiff
  • 661
  • 4
  • 13
0

OP: How to create a new list C that merges A and B based on their even/odd elements?

Assuming you have two lists with mixed odd/even elements in it, You could separate the odd/even elements and store them in separate lists, later iterating over them using zip():

A = [1,2,3,41,10,5,3,100]
B = [10,21,22,4,18,1,2,9]

odd_lst = []
even_lst = []


def is_even_odd(item):
    if int(item) % 2 == 0:
        even_lst.append(item)
    else:
        odd_lst.append(item)

for a_item, b_item in zip(A,B):
    is_even_odd(a_item)
    is_even_odd(b_item)


print([item for tup in zip(odd_lst, even_lst) for item in tup])

OUTPUT:

[1, 10, 21, 2, 3, 22, 41, 4, 5, 10, 1, 18, 3, 2, 9, 100]  # new list with odd,even elements sequence
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

I think your array is size 8. Since you are using numpy, try this example pls.

# merge two arrays as intermittent leaves (even and odd shuffle).
a = np.arange(5)
first_array = np.arange(0,10,2)
second_array = np.arange(1,11,2)
res = np.empty(10)
print (first_array)
print (second_array)
print (res)
res[a * 2] = first_array
res[a * 2 +1] = second_array
print (res)
user96265
  • 510
  • 5
  • 6