gpt4 book ai didi

python - 在 Python 中随机交错 2 个数组

转载 作者:太空狗 更新时间:2023-10-29 17:09:25 24 4
gpt4 key购买 nike

假设我有两个数组:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]

我想将这两个数组交错到一个变量“c”(注意“a”和“b”的长度不一定相等),但我不希望它们以确定的方式交错。简而言之,仅仅压缩这两个数组是不够的。我不想:

c = [1, 5, 2, 6, 3, 7, 4, 8, 9]

相反,我想要一些随机的东西,比如:

c = [5, 6, 1, 7, 2, 3, 8, 4, 9]

另请注意,结果数组“c”中保留了“a”和“b”的顺序。

我目前的解决方案需要一个 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

最佳答案

编辑:我认为最近的这个是最好的:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = [x.pop(0) for x in random.sample([a]*len(a) + [b]*len(b), len(a)+len(b))]

或者更高效:

c = map(next, random.sample([iter(a)]*len(a) + [iter(b)]*len(b), len(a)+len(b)))

请注意,上面的第一种方法修改了原始列表(如您的代码所做的那样),而第二种方法则没有。在 Python 3.x 上,您需要执行 list(map(...)),因为 map 返回一个迭代器。

原回答如下:

这是一个可以节省几行的选项:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]

c = []
tmp = [a]*len(a) + [b]*len(b)
while a and b:
c.append(random.choice(tmp).pop(0))

c += a + b

这是另一种选择,但只有当您知道所有元素都不是假的(没有 0, '', NoneFalse 或空序列):

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]

ratio = float(len(a)) / float(len(a) + len(b))
c = [(not a and b.pop(0)) or (not b and a.pop(0)) or
(random.random() < ratio and b.pop(0)) or a.pop(0)
for _ in range(len(a) + len(b))]

关于python - 在 Python 中随机交错 2 个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com