从列表中选择多个元素

时间:2017-06-08 21:30:13

标签: python list numpy random choice

我正在尝试为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')]

你知道怎么做这个输出吗?

2 个答案:

答案 0 :(得分:1)

如果您接受重复,random.choices将完成这项工作:

  

random.choices(人口,权重=无,*,cum_weights =无,k = 1)

     

返回从具有替换的人口中选择的k大小的元素列表。如果填充为空,则引发IndexError。

     

如果指定了权重序列,则根据相对权重进行选择。

>>> random.choices(['one', 'two', 'three'], weights=[0.2, 0.3, 0.5], k=2)
['one', 'three']

答案 1 :(得分:1)

如果您需要两个,只需告诉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() documentation

  

尺寸 int或元组,可选
  输出形状。如果给定的形状是例如(m, n, k),则绘制m * n * k个样本。默认值为None,在这种情况下会返回单个值。

     

替换布尔值,可选
  样品是否有替换

演示:

>>> 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')]
相关问题