如果我输入n
,将使用密钥count_dict
创建大小为n+1
的字典0...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'
答案 0 :(得分: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
>>> 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']})