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

在python 3.5中使用random.choices()的替代方法是什么,random,python-3.5,Random,Python 3.5,由于在Python3.5中没有random.choices(),因此该函数还有其他方法吗?按照Mark Dickinson的建议将代码从Python3.6复制到了 from itertools import accumulate as _accumulate, repeat as _repeat from bisect import bisect as _bisect import random def choices(population, weights=None, *, cum_weigh

由于在Python3.5中没有random.choices(),因此该函数还有其他方法吗?

按照Mark Dickinson的建议将代码从Python3.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)]

现在您可以和平地使用
选项
功能了

按照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)]

现在您可以和平地使用
选项
功能了

我已经阅读了文档部分,其中的方法只有在python 3.5中概率为整数时才有效。有没有其他方法我可以用
random.choices
是用Python编写的,因此您可以简单地将该方法复制到您的代码库中。我已经阅读了文档部分,其中的方法只有在Python 3.5中概率为整数时才有效。有没有其他方法我可以用
random.choices
是用Python编写的,因此您可以简单地将该方法复制到代码库中。