如何通过随机选择位置但不改变顺序来加入 2 python 个列表

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

我想通过随机选择索引而不改变顺序来加入 2 python 个列表,

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

随机给其中一个

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)

等等

我会做类似的事情:

伪代码

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
    ...

并确保在选择下一个随机列表以从中提取值时考虑 list_alist_b 的当前索引,以免索引超出范围。

您可以使用 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)

打印(例如):

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

这里的技巧不是直接打乱值而是对两个元组进行迭代。首先,我们用 两个 迭代器填充输出列表,这些迭代器被引用 len(a) + len(b) 次。打乱列表并在迭代器上使用 next() 函数按顺序获取实际值。