# Python 随机数函数 choices

**URL:** <https://www.isharkfly.com/t/python-choices/13399>\
**Category:** 程序语言\
**Tags:** python\
**Created:** [March 19, 2021, 3:05pm UTC](https://www.isharkfly.com/t/python-choices/13399 "2021-03-19T15:05:07Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![honeymoose](https://www.isharkfly.com/user_avatar/www.isharkfly.com/honeymoose/32/20796_2.png) [@honeymoose](https://www.isharkfly.com/u/honeymoose)\
**Post date:** [March 19, 2021, 3:05pm UTC](https://www.isharkfly.com/t/python-choices/13399/1 "2021-03-19T15:05:07Z")

</div>

Python 有关随机数工具类库中提供了一个随机数函数 `choices`。

这个随机数函数的主要目的是从给出的列表中生成随机数函数，同时还可以为每一个列表中的元素设置权重。

![python-choices -01](https://www.isharkfly.com/images/transparent.png)

可以考察使用下面的代码：

```auto
import random

# choices Function Test
print('')
my_list = ["apple", "banana", "cherry"]
print(random.choices(my_list, weights=[10, 1, 1], k=12))

```

上面的代码将会输出为：

```auto
['apple', 'apple', 'banana', 'apple', 'apple', 'apple', 'apple', 'cherry', 'banana', 'apple', 'apple', 'apple']

```

请注意的是，上面的代码中，我们使用了一个 weight 参数，这个参数的主要目的就是为了在随机数函数中针对 choices 函数设置权重，这个权重的设置将会导致上面列表中的第一个元素的权重更高。

最后一个 K = 12 参数的意思就是生成 12 个随机数列表。
