我有下面的代码,我试图在输入中每次出现时将 1 append 到元素的散列。
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.
list.append
是就地操作。所以它只是修改列表对象并且不返回任何东西。这就是为什么,默认情况下,None
会从 list.append
返回,而您要存储与此行中的键对应的内容
hash_table[elem] = hash_table[elem].append(1)
在您的情况下,您根本不需要 if
条件。
def test(Ar):
hash_table = {}
for elem in Ar:
hash_table.setdefault(elem, []).append(1)
print(hash_table)
因为,setdefault
会先在里面找keyelem
,找到了,然后返回对应的值。如果没有,那么它将创建键 elem
并使用传递给它的第二个参数作为值,然后返回值。
除了使用它,您还可以使用 collections.defaultdict
,就像这样
from collections import defaultdict
def test(Ar):
hash_table = defaultdict(list)
for elem in Ar:
hash_table[elem].append(1)
print(hash_table)
这与 setdefault
版本几乎相同
看起来您正在尝试查找元素的频率。在这种情况下,您可以简单地使用 collections.Counter
from collections import Counter
Ar = (1, 2, 3, 4, 5, 1, 2)
print Counter(Ar)
# Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1})
这将给出每个元素在传递的 iterable 中出现的次数。