如何创建第二个列表来存储每个卷的值?蟒蛇

时间:2015-09-27 19:13:56

标签: python-3.x

我创建了一个python骰子游戏,我希望它能够记录滚动的每个值 例如骰子滚动了6,3,2,4,5,1,6,4,4,3,2,4直到极限(到达)达到50以下是我的代码:

    import random
    throws = 0
    sixes = 0
    fives = 0
    fours = 0
    threes = 0
    twos = 0
    ones = 0
    reach = 50
    total = 0
    question = input ("Play Yes/No")
    if question == "Yes":
        question = True
    else:
        question = False
    while total < reach and question:
         roll = random.randint(1,6)
         throws +=1
         total += roll
         if roll == 6:
            sixes +=1
         elif roll == 5:
            fives +=1
         elif roll == 4:
            fours +=1
         elif roll == 3:
            threes +=1
         elif roll == 2:
            twos +=1
         elif roll == 1:
            ones +=1
         else :
            print("Try again later")
    if question :
        print("Total throws : ",throws)
        print("Total : ",total)
        print("Total 6's : ",sixes)
        print("Total 5's : ",fives)
        print("Total 4's : ",fours)
        print("Total 3's : ",threes)
        print("Total 2's : ",twos)
        print("Total 1's : ",ones)
    else :
        print("Your Loss!")

1 个答案:

答案 0 :(得分:0)

要回答您的问题,如何创建第二个列表以存储每个卷的值,您从一个空数组(order = [])开始,然后在每个卷后添加卷到数组的末尾(order.append(roll))。

还可以使用您的代码改进其他一些事项。

  • 由于正在对骰子进行计数,因此使用列表/数组更容易统计并只增加相应的索引
  • 如果您通过保存卷的顺序来跟踪卷筒,那么您不需要跟踪总和,您可以使用sum(order)
  • 如果您通过保存卷筒的顺序来跟踪卷筒,那么您无需跟踪卷筒的总数,您只需使用len(order)
  • 如果您使用数组而不是单个变量来跟踪计数,那么您可以将print语句放入for循环中

以下是改进的计划:

import random
rolls = [0]*6
order = []
limit = 50

question = input ("Play Yes/No")
if question == "Yes":
    question = True
else:
    question = False
while sum(order) < limit and question:
     roll = random.randint(1,6)
     order.append(roll)
     rolls[roll-1] += 1

if question :
    print("Order of rolls: ", order)
    print("Total throws : ",len(order))
    print("Total : ",sum(order))
    for i in range(len(rolls),0,-1):
        print("Total ", i, "'s : ", rolls[i-1])

else :
    print("Your Loss!")
相关问题