Discuss / Python / 尴尬

尴尬

Topic source

greatzues

#1 Created at ... [Delete] [Delete and Lock User]

不太明白下面这句的意思 :smile:

containsKey = 1 if key in self else 0

我的理解是传入的key若已存在,containsKey为1,若不存在,则containsKey为0

从而下面的判断:

if len(self)-containsKey >= self._capacity:

当前字典长度减去containskey若大于或等于字典容量,移除第一个key

if containsKey:

我测了下,当containskey为0时,即key不存在时,不执行此判断,因此仅在containskey为1时,删去同样的键值,最后再继承父类方法添加同样的进去。

OrderedDict.__setitem__(self, key, value)

因为先删去了同名的key再新增,所以新增的同名key,会改变原同名key的顺序

greatzues

#2 Created at ... [Delete] [Delete and Lock User]

推演过程如下:

>>> A = LastUpdatedOrderedDict(3)
>>> A['one'] = 1
add: ('one', 1)
>>> A['two'] = 2
add: ('two', 2)
>>> A['three'] = 3
add: ('three', 3)
>>> A['one'] = 11
set: ('one', 11)
>>> A['four'] = 4
remove: ('two', 2)
add: ('four', 4)
>>> A
LastUpdatedOrderedDict([('three', 3), ('one', 11), ('four', 4)])

  • 1

Reply