假设我有两个数组:
a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
我想将这两个数组交织到变量'c'(注意'a'和'b'不一定长度相等)但我不希望它们以确定的方式交错.简而言之,仅仅压缩这两个数组是不够的.我不想要:
c = [1, 5, 2, 6, 3, 7, 4, 8, 9]
Run Code Online (Sandbox Code Playgroud)
相反,我想要一些随机的东西:
c = [5, 6, 1, 7, 2, 3, 8, 4, 9]
Run Code Online (Sandbox Code Playgroud)
另请注意,'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 …Run Code Online (Sandbox Code Playgroud)