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

问题描述 投票:1回答:2

我正在尝试创建一个系统,它将以不同的数量滚动不同的多面骰子,以确定增加更多骰子的效果,以获得最高数量的机会。

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和边数之间滚动一个随机数,并将其附加到list_rolls列表中,并显示在print语句中:

        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列表似乎并没有像我预期的那样增长。

最后,在代码结束时,平均值始终是最后一个值,该值最终会进入最高值,而不是接近平均值。

以下是输出似乎可疑的示例:

>>> 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列表。

我觉得我在某个地方有一个缩进错误,但我已经尝试了多种写入方式,它似乎总是出现相同的。任何帮助将不胜感激。

python list while-loop append dice
2个回答
0
投票

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

希望这是有帮助的。


0
投票
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

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

© www.soinside.com 2019 - 2024. All rights reserved.