【问题标题】:Mixing ints and function pointers in python dict values在 python dict 值中混合整数和函数指针
【发布时间】:2013-09-17 04:26:55
【问题描述】:

我正在制作一个有限状态机来迭代一些文本以识别说话者、动词和引用。一切都很好,但我很沮丧,我不能让我的字典按照我想要的方式工作。我想使用这样的字典,它同时具有函数指针和整数作为值:

chars = ['a','b','c']
whatever = ['cheese']
state = 0

def function():
    # don't know what's going on, ask user to check

transitions = {
0: {chars: 1, whatever: 2, '“': 4},
1: {chars: 3, '“': function},
etc.
}

for item in data:
    for transition in transitions[state]:
        if item in transition or transition in item:
            state = transitions[state][item]

但是,如果找到该函数,则此代码不会调用该函数,或者如果我让它调用该函数,则在调用 int 时会出错。

PS 我不想使用库等。

【问题讨论】:

  • 这段代码甚至无法编译:你不能让一个列表有一个字典键(它应该是def function():,但我想这只是一个错字)。 state 被用作 rhs 上的索引,没有被定义。
  • 是的!只是错别字,抱歉。我修好了它们。我想我在晚上太晚了快速复制/粘贴+概括我的代码。

标签: python dictionary function-pointers state-machine


【解决方案1】:

您可以使用对象类型来决定如何处理它。我不想涉及代码的其他问题,但对于基本思想,这是一个返回 int 或根据值类型调用函数的函数。

def action(value):
    if isinstance(value, int):
        return value
    elif callable(value):
        return value()
    else:
        raise ValueError("action does not work with %s objects" % type(value))

【讨论】:

  • @Brian - 哎呀,我确实做到了。
  • 当然:我没有想到这一点。现在我的代码在代码中作为 if/else 执行此操作,但我想让它在字典中更加紧凑和独立。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 2017-03-16
  • 2015-10-26
  • 2017-07-25
  • 1970-01-01
相关资源
最近更新 更多