【问题标题】:python access dictionary that has two keys using only one keypython访问字典,只有一个键有两个键
【发布时间】:2015-10-31 16:53:10
【问题描述】:

我目前正在使用 Q learning,并且我有一本字典 Q[state, action] 每个状态都可以是任何东西,即字符串、数字、列表……取决于应用程序。每个状态有 3 或 4 个可能的动作。对于每个状态,我需要找到具有最高 Q 值的动作。问题是我不知道如何直接从具有两个键的字典中访问状态具有的所有可能操作,因此我尝试使用 for 循环:

for statex, actionx in self.array:
    if statex == state and (actionx != None):
         y[actionx] = self.array[statex, actionx]
y.argMax()

哪里 argMax()

def argMax(self):
    """
    Returns the key with the highest value.
    """
    if len(self.keys()) == 0: return None
    all = self.items()
    values = [x[1] for x in all]
    maxIndex = values.index(max(values))
    return all[maxIndex][0]

问题是计算时间太长。有什么想法可以让它更快,可能是通过消除 for 循环?

【问题讨论】:

  • 尝试使用iter(self.array)iter(self.items())
  • 获取以键为第一个元素、值为第二个元素的元组列表,并在其上使用迭代器。通常,这在内存方面工作得更快

标签: python dictionary machine-learning q-learning


【解决方案1】:

如果你使用字典字典会快得多:

    self.array[state][action]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2015-12-22
    • 1970-01-01
    相关资源
    最近更新 更多