假设我有两个数组:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
我希望将这两个数组交错到变量'c'中(请注意'a'和'b'的长度不一定相等),但我不希望它们以确定的方式交错。简而言之,仅仅使用zip这两个数组是不够的。我不希望:
c = [1, 5, 2, 6, 3, 7, 4, 8, 9]
相反,我想要一些随机的东西,比如:
c = [5, 6, 1, 7, 2, 3, 8, 4, 9]
还需要注意,'a'和'b'的顺序在生成的数组'c'中保留。
我当前的解决方案需要使用for循环和一些随机数生成。我不喜欢它,希望有人能指点我一个更好的解决方案。
# resulting array
c = []
# this tells us the ratio of elements to place in c. if there are more elements
# in 'a' this ratio will be larger and as we iterate over elements, we will place
# more elements from 'a' into 'c'.
ratio = float(len(a)) / float(len(a) + len(b))
while a and b:
which_list = random.random()
if which_list < ratio:
c.append(a.pop(0))
else:
c.append(b.pop(0))
# tack on any extra elements to the end
if a:
c += a
elif b:
c += b