【问题标题】:Two dimensional associative array in PythonPython中的二维关联数组
【发布时间】:2011-10-05 11:50:31
【问题描述】:

我有一个带有“A”“B”“C”之类的术语的 set()。我想要一个二维关联数组,以便我可以执行类似 d['A']['B'] += 1 的操作。这样做的pythonic方式是什么,我在想一个dicts的dicts。有没有更好的办法。

【问题讨论】:

  • 你能举一个预期结果的例子吗?

标签: python associative-array


【解决方案1】:

dict 的 dict 是一种方式。

另一种方法是简单地使用元组:

d[('A','B')] += 1

正如 TokenMacGuy 所指出的,括号是可选的:

d['A','B'] += 1

根据您的代码,这可能会简化一些事情。

【讨论】:

  • 括号不是必须的,python 会自动从逗号分隔的项目索引中创建元组(主要是为了支持array/numpy
【解决方案2】:

有两种明显的解决方案:一种,使用defaultdict将一个dict自动嵌套在另一个dict中

>>> d = collections.defaultdict(dict)
>>> d['a']['b'] = 'abc'
>>> d
defaultdict(<type 'dict'>, {'a': {'b': 'abc'}})
>>> 

另一种方法是使用 tuples 作为您的 dict 键:

>>> d = {}
>>> d['a','b'] = 'abc'
>>> d
{('a', 'b'): 'abc'}
>>> 

要获得 += 行为,请将 defaultdict(int) 替换为上述字典:

>>> d = collections.defaultdict(lambda:collections.defaultdict(int))
>>> d['a']['b'] += 1
>>> d
defaultdict(<function <lambda> at 0x18d31b8>, {'a': defaultdict(<type 'int'>, {'b': 1})})
>>> 
>>> d = collections.defaultdict(int)
>>> d['a','b'] += 1
>>> d
defaultdict(<type 'int'>, {('a', 'b'): 1})
>>> 

【讨论】:

    【解决方案3】:

    有什么理由不使用字典的字典吗?毕竟,它可以满足您的需求(尽管请注意,Python 中没有 ++ 这样的东西)。

    使用 dicts 的 dict 在风格上没有什么不好或非 Pythonic。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2010-10-25
      相关资源
      最近更新 更多