Python 随机数频率字典

-1 投票
4 回答
538 浏览
提问于 2025-04-18 10:44

我正在尝试写一个函数,生成两个随机整数,范围是1到6。然后我想创建一个字典,用来记录这两个整数相加的结果出现的频率。

这个功能是为了模拟掷两个骰子,掷x次。

这是我的代码:

def sim():
    dictionary = {}
    loop_value = 0
    total = 0

    while loop_value < 10:
        num_1 = random.randint(1, 6)
        num_2 = random.randint(1, 6)

        total = total + num_1 + num_2

        if value in dictionary:
            dictionary[total] += 1
        else:
            dictionary[total] = 1

        loop_value += 1
        print("Loop value", str(loop_value))
        print(dictionary)

这段代码只是把所有的值加在一起,所以并不是每个值都是独一无二的。我该怎么解决这个问题呢?

4 个回答

0

你需要的东西如下:

def sim(loop_value):
    dictionary = {}
    total = 0

    for i in xrange(loop_value): 
        num_1 = random.randint(1, 6)
        num_2 = random.randint(1, 6)

        total += num_1 + num_2

        if total in dictionary:
            dictionary[total] += 1
        else:
            dictionary.setdefault(total, 1)

        total = 0
        print("Loop value", str(loop_value))
        print(dictionary)

>>> sim(5)
>>> ('Loop value', '5')
{4: 1}
('Loop value', '5')
{4: 1, 7: 1}
('Loop value', '5')
{11: 1, 4: 1, 7: 1}
('Loop value', '5')
{8: 1, 11: 1, 4: 1, 7: 1}
('Loop value', '5')
{8: 1, 11: 1, 4: 1, 7: 2}
0

把这个

    if value in dictionary:
        dictionary[total] += 1

换成这个

    if total in dictionary:
        dictionary[total] += 1

我不太确定你是从哪里得到 value 的(在你的代码里没有定义),但几乎可以肯定这会导致你的 else 语句一直在执行。

1

虽然Martins的回答可能解决了你的问题,但你可以使用collections.Counter,这样可以更灵活地进行计数。

这里有个简单的例子:

>>> from collections import Counter
>>> Counter(random.randint(1, 6) + random.randint(1, 6) for x in range(10))
Counter({3: 3, 6: 3, 5: 2, 10: 1, 7: 1})

计数器其实是字典,所以你可以用和操作字典一样的方法来处理它们。

0
total = total + num_1 + num_2

我觉得你这里不应该加上 total,而是直接这样做:

total = num_1 + num_2

另外,把 value 替换成 total,就像之前的帖子提到的那样。

if total in dictionary:
    dictionary[total] += 1
else:
    dictionary[total] = 1

撰写回答