简体   繁体   English

为什么我的for循环运行的次数超过我指定的次数?

[英]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? 我希望这能从stats字典中退回9个键,但我却得到27个键。为什么会发生这种情况,以及如何获得想要获得的结果?

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). 对于每次迭代,您都将打印3个统计信息(stat1,stat2,stat3)。 So, If you iterate over stats dictionairy (9 loops) it gives you 27 printed stats. 因此,如果您遍历统计字典(9个循环),它将为您提供27个打印统计。

You want the loop controlled by level , not stats : 您希望循环由level而不是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. 但是,这不能保证您将获得三个不同的统计信息,因为对random.choice每次调用都是独立的。 Instead, use random.sample : 而是使用random.sample

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

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

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