gpt4 book ai didi

python - 将值附加到列表并添加到字典

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:43 24 4
gpt4 key购买 nike

我的 binary_list 是“000”、“001”、“010”、……的字符串列表。

我正在尝试将每个位串中 1 的数量添加到字典中。将为字符串中出现的每个 1 的数量创建大小为 n 的字典

我似乎无法将位串附加到列表中,然后将其添加到字典中。当我运行代码时,我得到:

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

最佳答案

>>>strings=["000","001","010","011","100","101","110","111"]
>>>d={}
>>>for s in strings:
... count = s.count("1")
... if count not in d:
... d[count]=[]
... d[count].append(s)

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

关于python - 将值附加到列表并添加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19253662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com