为什么切片对象在python中不可散列

2024-04-18 08:19:19 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么python中的slice对象不可散列:

>>> s = slice(0, 10)
>>> hash(s)
TypeError                                 Traceback (most recent call last)
<ipython-input-10-bdf9773a0874> in <module>()
----> 1 hash(s)

TypeError: unhashable type

它们似乎是不变的:

^{pr2}$

上下文,我想制作一个字典,将python int或slice对象映射到某些值,如下所示:

class Foo:
   def __init__(self):
       self.cache = {}
   def __getitem__(self, idx):
       if idx in self.cache:
           return self.cache[idx]
       else:
           r = random.random()
           self.cache[idx] = r
           return r

作为解决方法,我需要特殊情况切片:

class Foo:
   def __init__(self):
       self.cache = {}
   def __getitem__(self, idx):
       if isinstance(idx, slice):
           idx = ("slice", idx.start, idx.stop, idx.step)
       if idx in self.cache:
           return self.cache[idx]
       else:
           r = random.random()
           self.cache[idx] = r
           return r

这没什么大不了的,我只想知道这背后是否有什么道理。在


Tags: 对象inselfcachereturniffooinit
2条回答

Python bug tracker

Patch # 408326 was designed to make assignment to d[:] an error where d is a dictionary. See discussion starting at http://mail.python.org/pipermail/python-list/2001-March/072078.html .

切片被特别地设置为不易损坏,因此如果您试图将切片分配给dict,就会出现错误

不幸的是,邮件列表存档链接看起来不稳定。引文中的链接是死的,alternate link I suggested using也死了。我能给您指出的最好的方法是that entire month of messages的存档链接;您可以按Ctrl-F键,{找到相关的(以及一些误报)。在

作为解决方法,您可以使用支持pickling slice对象的__reduce__()方法:

>>> s
slice(2, 10, None)
>>> s1=s.__reduce__()
>>> s1
(<class 'slice'>, (2, 10, None))

虽然切片是不可散列的,但它的表示是:

^{pr2}$

你可以很容易地重建切片:

>>> slice(*s1[1])
slice(2, 10, None)

相关问题 更多 >