Python中的 random.choices() 方法
Choices()方法从列表中返回多个随机元素并进行替换。您可以使用weights
参数或cum_weights
参数权衡每个结果的可能性。元素可以是字符串、范围、列表、元组或任何其他类型的序列。
Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)
Parameters :
1. sequence is a mandatory parameter that can be a list, tuple, or string.
2. weights is an optional parameter which is used to weigh the possibility for each value.
3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated
4. k is an optional parameter that is used to define the length of the returned list.
注意:此方法与 random.choice() 不同。
例子:
import random
mylist = ["geeks", "for", "python"]
print(random.choices(mylist, weights = [10, 1, 1], k = 5))
注意:每次输出都会不同,因为系统会返回随机元素。
输出:
['geeks', 'geeks', 'geeks', 'for', 'for']
实际应用:打印一个包含 6 个项目的随机列表。
import random
mylist = ["apple", "banana", "mango"]
print(random.choices(mylist, weights = [10, 1, 1], k = 6))
注意:每次使用choices()函数时,输出都会发生变化。
输出:
['apple', 'banana', 'apple', 'apple', 'apple', 'banana']