从列表中选择超过 1 个元素

Choosing more than 1 element from the list

我正在尝试为 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(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to the relative weights.

>>> 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() documentation:

size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

replace : boolean, optional
Whether the sample is with or without replacement

演示:

>>> 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')]