Mybinary_list
是“000”、“001”、“010”、....的字符串列表
我正在尝试将每个位串中 1 的数量添加到字典中。将创建字典,其大小n
为字符串中出现的每个 1 的数量
我似乎无法将位串附加到列表中,然后将其添加到字典中。当我运行代码时,我得到:
input: sortbits(3)
000
001
010
011
100
101
110
111
{0: [], 1: [], 2: []}
正确的输出是:
000
001
010
011
100
101
110
111
{0: [000], 1: [001, 010, 100], 2: [011,101, 110], 3: [111]}
我的代码:
def sortbit(n):
max_num = 2**n
binary_list = []
for x in range(0,max_num):
stringy = []
for a in range(n):
stringy.append(str(x%2))
x //= 2
print ''.join(reversed(stringy))
stringy_list = ''.join(reversed(stringy))
binary_list.append(stringy_list)
count_dict = dict.fromkeys(range(0,n+1))
for element in binary_list:
count = 0
value_list = []
for character in element:
if character == '1':
count += 1
for y in count_dict:
if y == str(count):
value_list.append(element)
count_dict[y] = value_list
print count_dict