为什么我的 for 循环被忽略了?

Why is my for loop being ignored?

import random
stats = [0]*6
fixed = [1,2,3,4,5,6]
def single_roll(n,fixed=(),sides=6):
    for x in range(0,n):
        dice = random.randint(1,6)
        if dice == 1:
           stats[0] += 1
        elif dice == 2:
           stats[1] += 1
        elif dice == 3:
           stats[2] += 1
        elif dice == 4:
           stats[3] += 1
        elif dice == 5:
           stats[4] += 1
        elif dice == 6:
           stats[5] += 1
x = list(zip(fixed, stats))
single_roll(10)
print (x)

当我尝试 运行 时,为什么它会为统计列表生成一个包含 0 的列表?为什么程序中没有使用我的 for 循环?谢谢

您在调用 single_roll 函数之前创建了 x,此时 stats 列表全为零。 stats 用于计算 x 的值,但之后 x 是一个全新的列表,与 stats 没有任何联系,所以即使 single_roll 修改了 stats, x 不变。您可以在调用后放置作业:

single_roll(10)
x = list(zip(fixed, stats))

你所要做的就是:

import random
stats = [0]*6
fixed = [1,2,3,4,5,6]
def single_roll(n,fixed=(),sides=6):
    for x in range(0,n):
        dice = random.randint(1,6)
        if dice == 1:
           stats[0] += 1
        elif dice == 2:
           stats[1] += 1
        elif dice == 3:
           stats[2] += 1
        elif dice == 4:
           stats[3] += 1
        elif dice == 5:
           stats[4] += 1
        elif dice == 6:
           stats[5] += 1


single_roll(10)      
x = list(zip(fixed, stats))  #place this after the function call
print (x)

现在这将输出:

[(1, 1), (2, 2), (3, 2), (4, 2), (5, 2), (6, 1)]