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

标签 python python-2.7

我的 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/

相关文章:

python - 如何在 Python 中的新型类上正确覆盖 __setattr__ 和 __getattribute__?

python - Openerp : onChange event to create lines on account move

python - 在python中获取第一个和第二个管道之间的数据

python - 常见的 lisp 格式指令来打印列表

python - 返回字典中的最大值

django - 错误: invalid command 'bdist_wheel'

python - 检查IP地址版本的最快方法

python - Twisted 和 pyapns 的推送通知错误

macos - Matplotlib 在交互模式下绘图时失败并挂起

python - 如何在Odoo8中调用其他 Sprite 的 Sprite ?