标题有点棘手,但这就是我想表达的意思: 我有2个数组
A = [1, 2, 3, 4, 5]
B = ['a', 'b', 'c', 'd', 'e']
我想合并并改组它们,但保持其顺序,如下所示:
C = [1, 2, 'a', 3, 'b', 'c', 4, 'd', 'e', 5]
如您所见,它们是随机合并的,但它们保持各自的顺序。我该怎么办?
请注意,按照我的要求进行合并时,合并不一定必须处于任何特定的分布。
答案 0 :(得分:2)
尝试一下:
import random
A = [1, 2, 3, 4, 5]
B = ['a', 'b', 'c', 'd', 'e']
output = []
while A and B:
# choosing randomly from which list to pick the first element
if bool(random.getrandbits(1)):
output.append(A.pop(0))
else:
output.append(B.pop(0))
output += A + B # since the while loop stops when the first list is empty, we should add the rest of the elements to the end of the output
print(output)