Python: 滚动多面骰子不附加到列表

Python: Rolling multi-sided dice not appending to list

我正在尝试创建一个系统,该系统将掷出不同数量的不同多面骰子,以确定添加更多骰子对获得最高点数的机会的影响。

import random
from statistics import mean

#define the dice
class Dice:
    """these are the dice to roll"""
    def __init__(d, qty, sides):
        d.qty = qty
        d.sides = sides


q1d4 = Dice(1, 4)
q2d4 = Dice(2, 4)
q3d4 = Dice(3, 4)
q4d4 = Dice(4, 4)
#...removed extras for clarity
q5d20 = Dice(5, 20)
q6d20 = Dice(6, 20)

def Roll(Dice):

    i = 0
    while i < 10:
        single_rolls = []
        highest_of_rolls = []
        avg_of_highest = []
        qty = Dice.qty
        sides = Dice.sides

在这一行,我能够成功地在 1 和边数之间滚动一个随机数,并将其附加到列表 single_rolls 中,这在打印语句中显示:

        for q in range(qty):
            #rolls a single dice "qty" times and appends the result to single_rolls
            single_rolls.append(random.randint(1, sides))
            print(single_rolls)

然后我尝试将 single_rolls 列表中的最高数字附加到 while 循环中的 highest_of_rolls 列表中,用于每次滚动迭代,然后对其进行平均:

        highest_of_rolls.append(max(single_rolls))
        print(highest_of_rolls)
        i += 1

    avg_of_highest = mean(highest_of_rolls)
    print(avg_of_highest)

虽然我 运行 它似乎没有附加到 highest_of_rolls 列表。从 print 语句看来,它似乎成功地从两个卷中找到了最高的数字,但是 highest_of_rolls 列表似乎并没有像我预期的那样增长。

最后,在代码的末尾,平均值始终只是本应进入 highest_of_rolls 的最后一个值,而不是接近平均值的任何位置。

这是一个看似可疑的输出示例:

>>> Roll(q2d20)
[11]
[11, 14]
[14]
[15]
[15, 1]
[15]
[4]
[4, 9]
[9]
[15]
[15, 2]
[15]
[1]
[1, 16]
[16]
[9]
[9, 3]
[9]
[18]
[18, 9]
[18]
[20]
[20, 11]
[20]
[13]
[13, 5]
[13]
[20]
[20, 10]
[20]
20

即使是我对统计的简单理解也能看出 20 不是 20 以下的多个数字的平均值,而且这个数字波动很大,而且总是只是最后一个进入 highest_of_rolls 列表的数字.

我觉得我某处有缩进错误,但我尝试了多种写法,结果似乎总是一样。任何帮助将不胜感激。

他没有附加到 highest_of_rolls 因为在你的 while 循环开始时你每次都重置变量。 while 语句前必须定义highest_of_rolls,否则每次掷骰子都会清空变量

希望这对您有所帮助。

def Roll(Dice):

i = 0
while i < 10:
    single_rolls = []
    highest_of_rolls = [] # <--- reseting highest_of_rolls to a blank list
    avg_of_highest = []
    qty = Dice.qty
    sides = Dice.sides

解决方案

def Roll(Dice):

i = 0
highest_of_rolls = [] # <--- move outside of loop, won't erase items

while i < 10:
    single_rolls = []
    avg_of_highest = []
    qty = Dice.qty
    sides = Dice.sides

此外,您可以使用 for i in range(10) 而不是使用 while i < 10: 并增加 i,没有什么不同只是消除了为每个循环增加 i 的需要。