Kur*_*lar 3 python dictionary list append
我有下面的代码,我试图在输入中每次出现一个元素的哈希值时附加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)
Run Code Online (Sandbox Code Playgroud)
输出:
{1: None, 2: None, 3: [1], 4: [1], 5: [1]}
Run Code Online (Sandbox Code Playgroud)
预期产出:
{1: [1,1], 2: [1,1], 3: [1], 4: [1], 5: [1]}
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么没有进入追加.请解释发生了什么.
注意:
在键入其他部分时,
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.
Run Code Online (Sandbox Code Playgroud)
这list.append是一个就地操作.所以它只是修改列表对象而不返回任何内容.这就是默认情况下None返回的原因,list.append您将存储与此行中的键对应的内容
hash_table[elem] = hash_table[elem].append(1)
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您根本不需要if条件.
def test(Ar):
hash_table = {}
for elem in Ar:
hash_table.setdefault(elem, []).append(1)
print(hash_table)
Run Code Online (Sandbox Code Playgroud)
因为,setdefault首先elem会找到它中的键并找到一些东西,然后它会返回与之对应的值.如果没有那么它将创建密钥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)
Run Code Online (Sandbox Code Playgroud)
这与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})
Run Code Online (Sandbox Code Playgroud)
这将给出每个元素在迭代传递中出现的次数.