0

我想从给定的字典中创建一个包含 3 个选项的样本。字典长度可以是可变的。

我在之前的代码中所做的是创建一个加权值字典,在本例中是 12 个值和键。

虽然无法从我的 random.choice 中检索样本。

使用蟒蛇 3

我的字典是

dictionary = {'Three': 14.4, 'Five': 11.2, 'Two': 14.4, 'Thirteen': 3.3, 'One': 17.6, 'Seven': 3.3, 'Nine': 3.3, 'Ten': 3.3, 'Twelve': 3.3, 'Eight': 3.3, 'Four': 12.0, 'Six': 10.4}

我尝试从字典的随机选择中检索 3 个样本。

my_sample = random.sample(random.choice(dictionary), 3)
print(my_sample)

但是得到这个错误

Traceback (most recent call last):
  File "c_weights.py", line 38, in <module>
    my_sample = random.sample(random.choice(dictionary), 3)
  File "/usr/lib64/python3.3/random.py", line 252, in choice
    return seq[i]
KeyError: 11

试图得到

My_sample = ('One', 'Four','Twelve') 例如。

编辑:只是为了清楚我正在努力的是。

('One', 'Four','Twelve')
('Two', 'One','Six')
('Four', 'Two','Five')
('One', 'Eight','Two')
('Thirteen', 'Three','Six')

如此独特的集合建立在字典内的加权概率上(或者如果更好的话,则为元组)

4

2 回答 2

2

您无法成功应用于random.choice()字典 - 它是用于序列的函数,而不是用于映射的函数。

尝试:

random.sample(dictionary, 3)

这将返回一个列表,其中包含来自 dict 的 3 个随机键。

于 2013-11-09T22:42:33.957 回答
1

好的,这可能充满了错误/统计错误,但这对你来说是一个起点,我现在没有更多时间。这也是非常低效的!说了这么多,希望对大家有帮助:

import random

d= {'Three': 14.4, 'Five': 11.2, 'Two': 14.4, 'Thirteen': 3.3, 'One': 17.6, 'Seven': 3.3, 'Nine': 3.3, 'Ten': 3.3, 'Twelve': 3.3, 'Eight': 3.3, 'Four': 12.0, 'Six': 10.4}
total_weight = sum(d.values())
n_items = 3
random_sample = list()
d_mod = dict(d)

for i in range(n_items):
    random_cumulative_weight = random.uniform(0, total_weight)
    this_sum = 0.0
    for item, weight in d_mod.items():
        this_sum += weight
        if this_sum >= random_cumulative_weight:
            random_sample.append(item)
            break
    del(d_mod[item])
    total_weight -= this_sum

random_sample

产生 ['Seven', 'Nine', 'Two'] 等。

于 2013-11-09T23:12:40.600 回答