【发布时间】:2016-04-21 07:20:59
【问题描述】:
我有下面的代码,我试图在输入中每次出现时将 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.
【问题讨论】:
标签: python list dictionary append