简体   繁体   中英

Why does my for loop run more times than I specify?

I expect this to give me back 9 keys from the stats dictionary, but instead I get 27. Why does this happen and how do I achieve the result I was trying to get?

import random

def statsGen():
    "Will generate an npc's stats"

    level = 3    
    const = random.randint(1, 20)
    str = random.randint(1, 20)
    dext = random.randint(1, 20)
    perc = random.randint(1, 20)
    intel = random.randint(1, 20)
    will = random.randint(1, 20)
    char = random.randint(1, 20)
    sp = random.randint(1, 20)
    luck = random.randint(1, 20)

    stats = {'Const':const,'Str':str,'Dext':dext,'Perc':perc,'Int':intel,'Will':will,'Char':char,'Sp':sp,'Luck':luck}

    for level in stats:
        stat1 = random.choice(list(stats))
        print(stat1)
        stat2 = random.choice(list(stats))
        print(stat2)
        stat3 = random.choice(list(stats))
        print(stat3)


statsGen()

For every iteration you print 3 stats (stat1, stat2, stat3). So, If you iterate over stats dictionairy (9 loops) it gives you 27 printed stats.

You want the loop controlled by level , not stats :

for _ in range(level):
    name, value = random.choice(stats.items())
    print("{} = {}".format(name, value))

However, there is no guarantee with this that you will get three different stats, as each call to random.choice is independent. Instead, use random.sample :

for name, value in random.sample(stats.items(), level):
    print("{} = {}".format(name, value))

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