由于 OrderedDict
具有列表(具有有序元素)和字典(使用键而不是索引)的特性,因此似乎可以使用键来进行切片。
>>> from collections import OrderedDict
>>> cities = OrderedDict((('san francisco', 650), ('new york', 212), ('shanghai', 8621), ('barcelona', 42423)))
>>> test['shanghai':] # I want all the cities from shanghai to the end of the list
TypeError: unhashable type
有趣的是,这不是由于OrderedDictionary.__getslice__
未被实现而导致的错误。我尝试向OrderedDict
添加自己的__getslice__
方法,但我一直遇到这个TypeError问题。似乎Python在将切片键传递给__getslice__
函数之前进行某种类型检查,以强制执行切片键仅为整数,这是多么不符合Python风格!
>>> class BetterOrderedDict(OrderedDict):
def __getslice__(self, start=None, end=None, step=1):
return 'potato'
>>> test = BetterOrderedDict((('one', 1), ('two', 2), ('three', 3), ('four', 4)))
>>> print test[1:4]
'potato' # ok this makes sense so far
>>> test['one':'four']
TypeError: unhashable type # WTF, strings are hashable!
所以我的问题是,为什么我不能实现非整数片段,是什么类型检查阻止了切片键甚至到达我的__getslice__
函数,并且我是否可以通过用绑定在C中实现我的BetterOrderedDict
来覆盖它?
slice('a','b')
是有效的。但是,[1,2,3][slice('a','b')]
会报错:TypeError: slice indices must be integers or None or have an __index__ method
。 - Adam Smith