简体   繁体   中英

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. 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 . This will mean that summ could be 0 or 1 which is not one of the keys contained in 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 . This allows my version to just register each roll with pairs[summ] += 1

You are generating 1000 random dice rolls, then counting them. This can be done efficiently using 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 is an integer + dictionary key, so the brackets doesn't really make sense in this situation.

You could also just loop through the keys because you aren't really using the value in that dict loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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