gpt4 book ai didi

python random.choices() not giving equal number of elements even if we give equal weights(即使我们给出了相同的权重,也没有给出相同数量的元素)

转载 作者:bug小助手 更新时间:2023-10-25 19:08:53 28 4
gpt4 key购买 nike



I want to create a random list with diffrent combinations of elements in the list. The count of each element appearing in the final list should same.

我想创建一个随机列表与列表中元素的不同组合。出现在最终列表中的每个元素的计数应该相同。


For example

例如


>>> set_sizes = [0, 3, 6, 12]
>>> target_list = random.choices(set_sizes, weights = [1, 1, 1, 1], k= 40)
>>> print (target_list.count(0), target_list.count(3), target_list.count(6), target_list.count(12))

8 10 12 10

Here I was expecting the count of all elements will be 10 since I give equal weights. But it is not same always. How can I modify the code to get the equal count for all elements ? Please help.

在这里,我期望所有元素的计数都是10,因为我给了相同的权重。但这并不总是一样的。如何修改代码以使所有元素的计数相等?请帮帮忙。


更多回答

It sounds like you want to shuffle a list, not choose from it. The entire point of choices is that each choice is independent from the others.

这听起来像是你想洗牌,而不是从中选择。选择的全部意义在于每个选择都是独立于其他选择的。

优秀答案推荐

You flip a coin 10 times, even through you have the same probability of getting the head with getting the tail each time, you don't always get 5 heads with 5 tails in the end. So the weighted random choice won't give what you want.

你掷10次硬币,即使你每次得到正面和反面的概率相同,你也不总是得到5个正面和5个反面。因此,加权随机选择不会给你想要的东西。


To get the target_list you want, simply create an ordered one, then shuffle it.

要获得所需的Target_List,只需创建一个有序的列表,然后对其进行置乱即可。


import random
from itertools import chain

set_sizes = [0, 3, 6, 12]
k = 10
target_list = list(chain.from_iterable([x] * k for x in set_sizes))
random.shuffle(target_list)

更多回答

Note that there is no need to build target_list that complicated. target_list = set_sizes * k is more efficient in just about every way.

注意,不需要构建那么复杂的TARGET_LIST。TARGET_LIST=SET_SIZES*k几乎在各个方面都更高效。

@MisterMiyagi you're right, don't know what I was thinking when writing that line of code. 😂

@MisterMiyagi你说得对,我写那行代码的时候不知道我在想什么。😂

Thank you very much @Tom and @ MisterMiyagi. It worked for me.

非常感谢“汤姆”和“宫城先生”。这对我很管用。

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com