how to join 2 python lists by selecting the position randomly but without changing the order

Viewed 27

I want to join 2 python lists by selecting index randomly without changing the order,

a=(1,2,3,4,5)
b=(a,b,c,d)

to one of these randomly

final = (a,b,1,c,2,3,4,d,5)
final = (1,a,b,2,c,3,4,d,5)
final = (a,b,c,1,2,d,3,4,5)

etc.

2 Answers

You can use random.shuffle:

from random import shuffle

a = (1, 2, 3, 4, 5)
b = ("a", "b", "c", "d")


out = [iter(a)] * len(a) + [iter(b)] * len(b)
shuffle(out)

out = [next(i) for i in out]
print(out)

Prints (for example):

['a', 'b', 'c', 1, 2, 'd', 3, 4, 5]

The trick here is not to shuffle directly the values but iterators over the two tuples. First we populate the output list with two iterators which are referenced len(a) + len(b) times. Shuffle the list and use next() function over the iterators to obtain the real values in order.

I would do something like:

Pseudocode

list_a_index = 0
list_b_index = 0
new_list = []
for i in range(len(list_a) + len(list_b)):
    which_list = chooseRandomList() #get random A or B
    if (which_list == list_a)
        new_list.append(list_a[list_a_index])
        list_a_index++
    #and the same for list_b
    ...

and make sure that you consider the current indices for list_a and list_b while you choose the next random list to pull value from to not go index out of range.

Related