【问题标题】:list query, functions in function列表查询,函数中的函数
【发布时间】:2010-08-02 08:37:08
【问题描述】:

我有一个功能:

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

之前,我创建了 3 个函数,但现在我定义了 main 函数和其中的其他 2 个函数。

【问题讨论】:

  • 您的实际问题是什么?为什么return theAction 不起作用?
  • 我需要使用def maxvalue函数中定义的列表。我需要通过反转它来返回它的第一个条目。
  • 你的缩进全错了。
  • 标识不是问题..我只需要知道如何返回列表的元素。从原来的地方复制代码,出现识别错误。我没有收到识别错误
  • @Shilpa:哪个列表的哪个元素?列表太多了。

标签: python function list


【解决方案1】:

您的代码非常不合 Python。记住 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多