2014-11-25 37 views
0

嗨即时试图创造一个游戏,计算机生成1和6之间的5个随机数字,但我的问题是我已经创建了将获得一个列表'1'在各自的部分取决于什么数字出现。例如如果计算机产生31534列表需要显示[1,0,2,1,1,0](因为有2个3的它填补2中的3插槽)只显示5张随机数,并没有别的另一个函数中使用从一个函数的变量(参数“骰子”填充)

from random import randint 

def rollDice(): 

    dice = [str(randint(1, 6)) for _ in range(5)] 
    print(dice) 
    return dice 

#----------------------------------------------------------------- 

def countVals(dice): 

    totals = [0, 0, 0, 0, 0] 
    for x in dice: 
     if x == 1: 
      totals = totals[1] + 1 
     elif x == 2: 
      totals = totals[2] + 1 
     elif x == 3: 
      totals = totals[3] + 1 
     elif x == 4: 
      totals = totals[4] + 1 
     elif x == 5: 
      totals = totals[5] + 1 

      print(totals) 
      return totals 

#------------------------------------------------------------------ 

rollDice() 
countVals() 
+1

countVals(rollDice()),并从rollDice删除STR(),为什么你需要转换为字符串。 – 2014-11-25 00:11:44

+0

请参阅http://www.python.org/dev/peps/pep-0008/代码样式准则。 – ThiefMaster 2014-11-29 12:13:55

回答

0

我认为这个问题是由您rollDice函数返回的结果是一个字符串列表。 countVals中的if - else语句然后落在原因例如'5' == 5 -> False。你可以修改rollDice返回廉政局的列表,而不是(不要你的整数转换为字符串):

def rollDice(): 

    dice = [randint(1, 6) for _ in range(5)] 
    print(dice) 
    return dice 

如果你绝对要rollDice返回字符串列表,你可以使用int的字符串转换为整数方法在你的countVals方法中。例如:int('5') -> 5,或者只是比较字符串而不是整数。 x == '5'

此外,请确保您将总计保存回总计列表中的正确索引(在rollDice中)。你可以这样做一点更简洁如下:totals[1] += 1,例如:

def countVals(dice): 

    totals = [0, 0, 0, 0, 0, 0] #alternatively could be 'totals = [0]*6' :) 
    for value in dice: 
     totals[value - 1] += 1 

    print(totals) 
    return totals 

(假设rollDice已被修改为返回一个整数列表)

你应该能够调用的方法如下totals = countVals(rollDice())以获得您的总计清单。

+0

好吧我会改变,但我得到一个错误参数“骰子”未填充 – paxyshack 2014-11-25 00:34:43

+0

你怎么调用这个'countVals(rollDice())'? – Ron 2014-11-25 00:38:22

+0

同时确保总数以六个元素(上面的修改代码)开始。数字可能是1,2,3,4,5或6. – Ron 2014-11-25 00:47:00

0

你可以尝试以下方法:

dice = rollDice() 
countVals(dice) 

另外你要修复的printreturn语句的缩进countVals()。目前,他们只会触发如果x==5。和萨尔瓦多·达利提到,无论是从rollDice()删除str或更改比较中countVals()x == '1'


编辑:

这里是你可以想怎么写你的脚本:

def rollDice(): 
    dice = [randint(1, 6) for _ in range(5)] 
    print(dice) 
    return dice 

def countVals(dice): 
    totals = [0, 0, 0, 0, 0] 
    for x in dice: 
     # x can be, 1-5. Index of totals can be 0-4. 
     totals[x-1] += 1 

     print(totals) 
     return totals 

dice = rollDice() 
countVals(dice) 
+0

我在哪里彪把“骰子= rollDice90”? – paxyshack 2014-11-25 00:29:00

1

我相信当你增加每个数字的计数你的错误就在于,

totals = totals[1] + 1 

是应该的,这取决于你的应用程序

totals[1] = totals[1] + 1 

而且您可以简化代码

def countVals(dice): 

    totals = [0, 0, 0, 0, 0] 
    for x in dice: 
     totals[x - 1] += 1 
    print (totals) 
    return totals 
相关问题