2010-08-02 27 views
-2

功能我有一個函數:列表查詢,在功能上

 I need to first reverse the list and then take an entry from it. 

早些時候,我正在3個功能,但現在我定義的主要功能和它的其他兩個功能。

+0

您的實際問題是什麼?爲什麼'return theAction'不起作用? – katrielalex 2010-08-02 08:40:34

+0

我需要使用def maxvalue函數中定義的列表。我需要通過顛倒它來返回它的第一個條目。 – Shilpa 2010-08-02 08:44:00

+0

您的縮進全部錯誤。 – kennytm 2010-08-02 08:49:37

回答

4

您的代碼非常和諧。記住Python不是C.

  1. 分號是可選的。
  2. if中的括號是可選的。
  3. 要獲取列表a的最後一個元素,請使用a[-1],而不是反轉a,然後獲取其第一個元素。
  4. 使用內置功能!修改後的maxagent可以簡單地使用max功能寫成:

    def maxagent(gamestate, depth): 
        actions = gamestate.getLegalActions(0) 
        filteredactions = filter(lambda action: action != Directions.STOP, actions) 
        # alternatives: 
        # filteredactions = filter(Directions.STOP.__ne__, actions) 
        # filteredactions = (a for a in actions if a != Directions.STOP) 
        bestaction = max(filteredactions, 
            key=lambda action: self.minvalue(
                  gamestate.generateSuccessor(0, action), 
                  depth, 1 
                 )) 
        return bestaction 
    

如果你需要的分數也考慮返回一個元組

def maxagent(gamestate, depth) 
    actions = gamestate.getLegalActions(0) 
    scores = ((self.minvalue(gamestate.generateSuccessor(0, a), depth, 1), a) 
       for a in actions if a != Directions.STOP 
      ) 
    return max(scores) 
... 
score, action = maxagent(gamestate, depth)