gpt4 book ai didi

random - 在 python 3.5 中使用 random.choices() 的替代方法是什么

转载 作者:行者123 更新时间:2023-12-05 06:22:51 32 4
gpt4 key购买 nike

既然 random.choices() 在 python 3.5 中不可用,那么这个函数是否有任何替代方法?

最佳答案

按照 Mark Dickinson 的建议将代码从 python 3.6 复制到

from itertools import accumulate as _accumulate, repeat as _repeat
from bisect import bisect as _bisect
import random
def choices(population, weights=None, *, cum_weights=None, k=1):
"""Return a k sized list of population elements chosen with replacement.
If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
"""
n = len(population)
if cum_weights is None:
if weights is None:
_int = int
n += 0.0 # convert to float for a small speed improvement
return [population[_int(random.random() * n)] for i in _repeat(None, k)]
cum_weights = list(_accumulate(weights))
elif weights is not None:
raise TypeError('Cannot specify both weights and cumulative weights')
if len(cum_weights) != n:
raise ValueError('The number of weights does not match the population')
bisect = _bisect
total = cum_weights[-1] + 0.0 # convert to float
hi = n - 1
return [population[bisect(cum_weights, random.random() * total, 0, hi)]
for i in _repeat(None, k)]

现在您可以安心地使用choices 功能了!

关于random - 在 python 3.5 中使用 random.choices() 的替代方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915023/

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