gpt4 book ai didi

python - 通过替换对 python 数组进行混洗

转载 作者:行者123 更新时间:2023-11-30 23:31:26 24 4
gpt4 key购买 nike

对 python 数组或列表进行替换的最简单方法是什么?

我知道random.shuffle(),但它会重新洗牌而不进行替换。

最佳答案

您正在寻找random.choice()调用列表理解:

[random.choice(lst) for _ in range(len(lst))]

这会生成一个与输入列表长度相同的列表,但值可以重复。

演示:

>>> import random
>>> lst = [1,2,4,5,3]
>>> [random.choice(lst) for _ in range(len(lst))]
[3, 5, 1, 4, 1]

关于python - 通过替换对 python 数组进行混洗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935050/

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