小编Spe*_*XCD的帖子

为什么dict.get(key)起作用但dict [key]不起作用?

我试图根据字符串中有1的数目将某些数字的二进制字符串组合在一起。

这不起作用:

s = "0 1 3 7 8 9 11 15"
numbers = map(int, s.split())
binaries = [bin(x)[2:].rjust(4, '0') for x in numbers]

one_groups = dict.fromkeys(range(5), [])
for x in binaries:
    one_groups[x.count('1')] += [x]
Run Code Online (Sandbox Code Playgroud)

预期的字典one_groups需要是

{0: ['0000'], 
 1: ['0001', '1000'], 
 2: ['0011', '1001'], 
 3: ['0111', '1011'], 
 4: ['1111']}
Run Code Online (Sandbox Code Playgroud)

但是我明白了

{0: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'], 
 1: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'], 
 2: ['0000', '0001', '0011', '0111', '1000', '1001', '1011', '1111'], 
 3: …
Run Code Online (Sandbox Code Playgroud)

python dictionary

17
推荐指数
2
解决办法
1684
查看次数

标签 统计

dictionary ×1

python ×1