从lis中选择多个元素

2024-09-30 18:13:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为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')]

你知道如何得到这个输出吗?你知道吗


Tags: 代码fromnumpy元素列表randomelements概率
2条回答

如果需要两个值,只需告诉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,以允许重复。参见^{} 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')]

如果接受重复项,^{}将执行以下操作:

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

相关问题 更多 >