python追加未添加到列表

2024-04-19 20:42:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习python,目前正在使用一个基本的掷骰子脚本。 2掷骰子直到他们都击中6。当它将打印达到定义的[6:6]所需的卷数时

这会重复2次以上,如图所示

for x in range(3):
        roll_dice()

我的问题是,当我尝试对运行列表求和时,它只会打印最后一次骰子滚动计数。我想我的run.append(count)不是在更新,而是在再次通过循环后重置

我知道我的代码的其余部分可能非常低效,但仍处于学习的早期阶段

import random

def roll_dice():
    dice_one = 0
    dice_two = 0
    count = 0
    run = []
    while True:
        dice_one = random.randrange(1,7)
        dice_two = random.randrange(1,7)
        count += 1
        print(dice_one, " ", dice_two)

        if dice_one +  dice_two == 12:
            print("----", count, "attempts----")
            break
    run.append(count)
    print(sum(run))

for x in range(3):
        roll_dice()

Tags: runin脚本for定义countrangerandom
3条回答

print(sum(run))只打印最后一次骰子滚动计数,因为run.append(count)在while循环之外。每次函数调用只调用一次。将它放在while循环中,它将在每次滚动模具时追加

只需将run.append(count)放在while循环中:

import random

def roll_dice():
    dice_one = 0
    dice_two = 0
    count = 0
    run = []
    while True:
        dice_one = random.randrange(1,7)
        dice_two = random.randrange(1,7)
        count += 1
        print(dice_one, " ", dice_two)

        if dice_one +  dice_two == 12:
            print("  ", count, "attempts  ")
            break
        run.append(count)
    print(sum(run))

for x in range(3):
        roll_dice()

正如其他人所指出的,正在run.append(count)循环之外调用While。因此,只有最后更新的count值被添加到run中。 通过在While循环中移动run.append(count),每次执行循环时都会更新它

相关问题 更多 >