我有以下代码,我正在尝试在输入中每次出现该元素时将1附加到其哈希值上。
def test(Ar):
hash_table = {}
for elem in Ar:
if elem not in hash_table:
hash_table.setdefault(elem,[]).append(1)
else:
hash_table[elem] = hash_table[elem].append(1)
print(hash_table)
Ar = (1,2,3,4,5,1,2)
test(Ar)
输出:
{1: None, 2: None, 3: [1], 4: [1], 5: [1]}
预期输出:
{1: [1,1], 2: [1,1], 3: [1], 4: [1], 5: [1]}
我很困惑为什么None会被添加到列表中。请解释一下发生了什么。
注意:
在键入else部分时,
hash_table[elem] = hash_table[elem].append(1) # the append() was not suggested at all by the IDE. I forcibly put it, hoping things will work.
defaultdict
有一个default_factory
属性,当设置为None
时,默认字典的行为就像普通字典一样。这对于希望使用 defaultdict 行为构建字典,但又想返回像普通字典一样的东西的函数特别有用。 - mgilson