获取字典中函数值的一些问题

时间:2018-09-21 23:45:09

标签: python dictionary

所以,我只是从Python开始,但是我试图在字典中实现函数(有点像C中的函数指针),但是我一直在坚持如何从函数中接收返回的值而没有一个错误。这是我的代码片段:

def main():
    numberOfDice = 5
    dice = rollDice(numberOfDice) #rolls dice thrice, returns a list of 5 integers
    scoreBoard(dice)   #displays Yahtzee scoreboard
    value = choice(dice)  #value = the category choice[1-13]
    whichCategory(value) 

def whichCategory(category):
    board = {
        6: numberOfSixes, # I have 1-13 filled, but just for example
        12: yahtzee       # this is just to save space.
        }
    board[category]()

def numberOfSixes(theDice):
    count = theDice.count(6)
    points = count * 6

    return points

def yahtzee(theDice):
    yahtzee = 0
    ones, twos, threes, fours, fives, sixes = countDice(theDice)
    # countDice() determines the amount that each number is present in the 
    # list and then returns those six variables.
    if any(x==5 for x in(ones, twos, threes, fours, fives, sixes)):
           yahtzee = 50

    return yahtzee

滚动3次后,我确定骰子(整数列表),然后从与whichCategory()一起选择的值中选择我的值,然后执行正确的计算,从这些函数中吐出正确的返回值,但是然后我会得到这样的错误(用于输入两个六点(12点)):

Traceback (most recent call last):
File "C:\python\Lib\idlelib\Yahtzee.py", line 407, in <module>
main()   # My call to main()
File "C:\python\Lib\idlelib\Yahtzee.py", line 18, in main
whichCategory(value)
File "C:\python\Lib\idlelib\Yahtzee.py", line 90, in whichCategory
board[category]()
TypeError: yahtzee() missing 1 required positional argument: 'theDice

这很有趣,因为它说错误是yahtzee()引起的,而不是6位,我相信这是因为它以某种方式得到12作为答案,并且在字典中调用了12th关键字。否则我会收到如下错误:

Traceback (most recent call last):
File "C:\python\Lib\idlelib\Yahtzee.py", line 407, in <module>
main()   # My call to main()
File "C:\python\Lib\idlelib\Yahtzee.py", line 18, in main
whichCategory(value)
File "C:\python\Lib\idlelib\Yahtzee.py", line 90, in whichCategory
board[category]()
KeyError: 50

请,我一直在寻找答案,但尚未找到答案。如果可能的话,我想将字典中函数的值返回给main()。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这未经测试,但是我认为问题在于在行board[category]()上,您调用了一个函数,但没有调用它需要的值。尝试进行这些更改

def main():
    numberOfDice = 5
    dice = rollDice(numberOfDice) #rolls dice thrice, returns a list of 5 integers
    scoreBoard(dice)   #displays Yahtzee scoreboard
    value = choice(dice)  #value = the category choice[1-13]
    whichCategory(value, dice) # pass dice

def whichCategory(category, dice):  # receive dice
    board = {
        6: numberOfSixes, # I have 1-13 filled, but just for example
        12: yahtzee       # this is just to save space.
        }
    board[category](dice)   # call with dice