将值附加到列表并添加到字典中

时间:2013-10-08 16:48:37

标签: 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

5 个答案:

答案 0 :(得分:5)

>>>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']}

答案 1 :(得分:3)

collections.defaultdict在这里更合适:

>>> from collections import defaultdict
>>> dic = defaultdict(list)
for i in xrange(8):
    bi = format(i, '03b')
    dic[bi.count('1')].append(bi)
...     
>>> dic
defaultdict(<type 'list'>, {
0: ['000'],
1: ['001', '010', '100'],
2: ['011', '101', '110'],
3: ['111']})

答案 2 :(得分:2)

这有效:

>>> lst = ['000', '001', '010', '011', '100', '101', '110', '111']
>>> dct = {x:[] for x in xrange(max(map(len, lst))+1)}
>>> for item in lst:
...     dct[item.count('1')].append(item)
...
>>> dct
{0: ['000'], 1: ['001', '010', '100'], 2: ['011', '101', '110'], 3: ['111']}
>>>

所有这一切都应该非常简单,除了这个部分:max(map(len, lst))。这样做是计算lst中项目的最大长度。在这种情况下,最大长度为3.如果我要将另一个项目添加到lst,其中包含4个字符(例如“1010”),则最大长度为4.

您需要这个来确定dct中要放置的密钥数量。您需要的键数始终是lst + 1中项目的最大长度。

答案 3 :(得分:2)

from collections import defaultdict
def sortbit(n):
    d = defaultdict(list)
    max_val = 2**n
    for x in range(0,max_val):
       d[bin(x).count("1")].append("{0:0{1}b}".format(x,n))
    return d

我认为至少,这会使你的二进制值自动地变宽

>>> sortbit(3)
defaultdict(<type 'list'>, {0: ['000'], 1: ['001', '010', '100'], 2: ['011', '10
1', '110'], 3: ['111']})
>>> sortbit(4)
defaultdict(<type 'list'>, {0: ['0000'], 1: ['0001', '0010', '0100', '1000'], 2:
 ['0011', '0101', '0110', '1001', '1010', '1100'], 3: ['0111', '1011', '1101', '
1110'], 4: ['1111']})

答案 4 :(得分:2)

编辑:已更正 dict.getkeys 生成字典时出错

创建字典时,可以通过创建附加到同一行中每个键的列表来节省时间。这应该可以解决您的问题:

count_dict = {x:[] for x in range(0,n+1)}

你也可以用这种方式清理底部:

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

希望这有帮助!

相关问题