在python中按顺序组合数组并改组两个数组

标题有点棘手,但这就是我想表达的意思: 我有2个数组

A = [1, 2, 3, 4, 5]
B = ['a', 'b', 'c', 'd', 'e']

我想合并并改组它们,但要保持其顺序,如下所示:

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

如您所见,它们是随机合并的,但它们保持各自的顺序。我该怎么办?

评论
  • 闾丘山雁
    闾丘山雁 回复

    尝试这个:

    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)