简体   繁体   English

我有 dict -> pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12: 0} 尝试使用 for 循环更改键的值,但不起作用,

[英]I have dict -> pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0} trying to change the keys' values with for loop, not working,

import random

pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}

for i in range(0, 1001):

    d1 = random.randrange(0, 7)
    d2 = random.randrange(0, 7)
    summ = d1 + d2
    for k, v in pairs.items():
        if summ == k:
            k[v] += 1

What you meant to write was this:你的意思是这样写的:

import random

pairs = {2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0, 11:0, 12:0}

for i in range(0, 1001):

    d1 = random.randint(1, 6)
    d2 = random.randint(1, 6)
    summ = d1 + d2
    pairs[summ] += 1

print(pairs)

I see that you are searching though the pairs dict to find the right key which is a strange way to find a key.我看到您正在搜索pairs dict 以找到正确的密钥,这是一种奇怪的找到密钥的方法。 I now see the reason for that was because you are using randrange(0, 7) which produces numbers in the inclusive range of 0..6 .我现在看到原因是因为您使用的是randrange(0, 7) ,它产生的数字在0..6的包含范围内。 This will mean that summ could be 0 or 1 which is not one of the keys contained in pairs .这意味着summ可能是01 ,这不是pairs中包含的键之一。

By using randint(1, 6) this is a lot more like rolling a pair of dice and gives summ in the exact range of the keys you prepared in pairs .通过使用randint(1, 6)这更像是掷骰子,并在您pairs准备的键的确切范围内给出summ This allows my version to just register each roll with pairs[summ] += 1这允许我的版本只用pairs[summ] += 1注册每个卷

You are generating 1000 random dice rolls, then counting them.您正在生成 1000 个随机掷骰子,然后计算它们。 This can be done efficiently using collections.Counter .这可以使用collections.Counter有效地完成。

from collections import counter
from random import randint as r

pairs = dict(Counter(r(1, 6) + r(1, 6) for _ in range(1001)))

Just change k[v] += 1 to pairs[k] += 1只需将k[v] += 1更改为pairs[k] += 1

k is an integer + dictionary key, so the brackets doesn't really make sense in this situation. k是 integer + 字典键,所以在这种情况下括号没有意义。

You could also just loop through the keys because you aren't really using the value in that dict loop您也可以只遍历keys ,因为您并没有真正使用该 dict 循环中的值

for k in pairs.keys():
    if summ == k:
        pairs[k] += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM