[英]Choosing more than 1 element from the list
我试图为elements
每个元素做出选择,然后将elements
列表中的elements
与其优先选择(一,二或三)配对。 选择主要是针对元素的概率( weights
)进行的。 直到这里的代码:
from numpy.random import choice
elements = ['one', 'two', 'three']
weights = [0.2, 0.3, 0.5]
chosenones= []
for el in elements:
chosenones.append(choice(elements,p=weights))
tuples = list(zip(elements,chosenones))
产量:
[('one', 'two'), ('two', 'two'), ('three', 'two')]
我需要的是,为每个元素做出两个选择而不是一个选择。
预期的输出应如下所示:
[('one', 'two'), ('one', 'one'), ('two', 'two'),('two', 'three'), ('three', 'two'), ('three', 'one')]
您知道该怎么做吗?
如果您接受重复,则random.choices
将完成以下工作:
random.choices(人口,权重=无,*,cum_weights =无,k = 1)
返回从总体中选择的元素的ak大小列表,并进行替换。 如果填充为空,则引发IndexError。
如果指定了权重顺序,则根据相对权重进行选择。
>>> random.choices(['one', 'two', 'three'], weights=[0.2, 0.3, 0.5], k=2)
['one', 'three']
如果需要两个,只需告诉numpy.random.choice()
选择两个值即可。 在循环时将el
值包含为元组(无需使用zip()
):
tuples = []
for el in elements:
for chosen in choice(elements, size=2, replace=False, p=weights):
tuples.append((el, chosen))
或通过使用列表理解:
tuples = [(el, chosen) for el in elements
for chosen in choice(elements, size=2, replace=False, p=weights)]
通过设置replace=False
,您可以获得唯一的值; 删除它或将其显式设置为True
以允许重复。 请参阅numpy.random.choice()
文档 :
大小 : 整数或整数元组,可选
输出形状。 如果给定的形状是例如(m, n, k)
,则绘制m * n * k
样本。 默认值为None
,在这种情况下,将返回一个值。replace : 布尔值,可选
样品是否更换
演示:
>>> from numpy.random import choice
>>> elements = ['one', 'two', 'three']
>>> weights = [0.2, 0.3, 0.5]
>>> tuples = []
>>> for el in elements:
... for chosen in choice(elements, size=2, replace=False, p=weights):
... tuples.append((el, chosen))
...
>>> tuples
[('one', 'three'), ('one', 'one'), ('two', 'three'), ('two', 'two'), ('three', 'three'), ('three', 'two')]
>>> [(el, chosen) for el in elements for chosen in choice(elements, size=2, replace=False, p=weights)]
[('one', 'one'), ('one', 'three'), ('two', 'one'), ('two', 'three'), ('three', 'two'), ('three', 'three')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.