对 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/