2

如果我输入,将使用键创建一个大小n的字典。count_dictn+10...n

我想解析一个名为的列表,该列表binary_list包含大小字符串n,每个字符串都由 0 或 1 组成。每次解析都会计算字符串中 1 的数量,并将append每个字符串中的 1 数量计算为相应的键

前任:

{0:['000'], 1:['001','010','100'] , 2:['011', '101', '110'] , 3:['111']}

我执行此操作的代码:

count_dict = dict.fromkeys(range(0,n+1))

for element in binary_list:
    count_dict[element.count('1')].append(element)

错误”

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "facebook_prob.py", line 23, in sortbit
    count_dict[element.count('1')].append(element)
AttributeError: 'NoneType' object has no attribute 'append'
4

1 回答 1

5

在不指定第二个参数的情况下,默认值为 None。(见dict.fromkeys

>>> n = 3
>>> count_dict = dict.fromkeys(range(0,n+1))
>>> count_dict
{0: None, 1: None, 2: None, 3: None}

除此之外,由创建的值dict.fromkeys由所有条目共享。

>>> count_dict = dict.fromkeys(range(0,n+1), [])
>>> count_dict
{0: [], 1: [], 2: [], 3: []}
>>> count_dict[0] is count_dict[1]
True

collections.defaultdict更合适。

>>> from collections import defaultdict
>>> count_dict = defaultdict(list)
>>> count_dict[0].append('000')
>>> count_dict[1].append('001')
>>> count_dict[1].append('010')
>>> count_dict
defaultdict(<type 'list'>, {0: ['000'], 1: ['001', '010']})
于 2013-10-09T06:20:33.750 回答