【问题标题】:Python dictionary with list keyword带有 list 关键字的 Python 字典
【发布时间】:2011-12-30 11:55:29
【问题描述】:

我正在编写一个 N 阶马尔可夫链。

它是这样的:

class Chain:
 def __init__(self, order):
  self.order = order
  self.state_table = {}
 def train(self, next_state, *prev_states):
  if len(prev_states) != self.order: raise ValueError("prev_states does not match chain order")
  if prev_states in self.state_table:
   if next_state in self.state_table[prev_states]:
    self.state_table[prev_states][next_state] += 1
   else:
    self.state_table[prev_states][next_state] = 0
  else:
   self.state_table[prev_states] = {next_state: 0}

不幸的是,列表和元组是不可散列的,我不能将它们用作字典中的关键字... 希望我已经很好地解释了我的问题,以便您了解我试图实现的目标。

关于如何为字典关键字使用多个值有什么好的想法吗?

后续问题:

我不知道元组是可散列的。 但是哈希的熵似乎很低。元组是否可能存在哈希冲突?!

【问题讨论】:

  • 列表和元组是不可散列的 - 元组是可散列的。 (如果他们的内容是可散列的,正如@larsmans 正确指出的那样)
  • 一个空格缩进?读起来非常难看。您应该遵循 PEP-8 并使用 4 空格缩进。
  • eumiro,谢谢!添加了有关哈希冲突的后续问题

标签: python dictionary markov-chains


【解决方案1】:

元组当它们的内容是可散列的。

>>> a = {}
>>> a[(1,2)] = 'foo'
>>> a[(1,[])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

至于碰撞,当我尝试一堆非常相似的元组时,我发现它们被映射得很远:

>>> hash((1,2))
3713081631934410656
>>> hash((1,3))
3713081631933328131
>>> hash((2,2))
3713082714462658231
>>> abs(hash((1,2)) - hash((1,3)))
1082525
>>> abs(hash((1,2)) - hash((2,2)))
1082528247575

【讨论】:

    【解决方案2】:

    您可以将元组用作字典键,只要它们的内容是可散列的(正如@larsman 所说),它们就是可散列的。

    不用担心冲突,Python 的 dict 会处理它。

    >>> hash('a')
    12416037344
    >>> hash(12416037344)
    12416037344
    >>> hash('a') == hash(12416037344)
    True
    >>> {'a': 'one', 12416037344: 'two'}
    {'a': 'one', 12416037344: 'two'}
    

    在这个例子中,我使用了一个字符串和一个整数。但它对元组的工作方式相同。只是不知道如何找到两个具有相同哈希值的元组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      • 2018-06-17
      • 2015-12-21
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      相关资源
      最近更新 更多