我无法将大型列表放入字典加字典中的元组

时间:2015-03-27 22:08:44

标签: python list dictionary reduce

这是问题所在。我正在创建一个包含abc ... 789的所有组合的列表。我想创建该列表的字典,然后将其发送到地图功能。

def enumerate(length, possibles):
   ret = []
   if length == 1:
     return list(possibles) 
   else:
     subs = enumerate(length -1, possibles)
     ret = ret + subs
     for ch in possibles:
       for sub in subs:
         ret.append(str(ch) + str(sub))
return ret



datasource = dict(enumerate(4,"abcdefghijklmnopqrstuvwxyz0123456789"))

我收到了这个错误:

Traceback (most recent call last):
   File "ex_passcrack.py", line 27, in <module>
   datasource = dict(enumerate(4,"abcdefghijklmnopqrstuvwxyz0123456789"))
ValueError: dictionary update sequence element #0 has length 1; 2 is required

我不知道这意味着什么。任何帮助表示赞赏。

我必须补充这个问题。任何人都可以告诉我如何建立一个类似的字典       {0:&#39; a&#39;,&#39; foo&#39;,1:&#39; b&#39;,&#39; foo&#39;,2:&#39; aa&#39 ;,&#39; foo&#39;,3:&#39; ab&#39;,&#39; foo&#39;,4:&#39; ba&#39;,&#39; foo&#39; ,5:&#39; bb&#39;,&#39; foo&#39;}

如果它看起来不对,我很抱歉(因为我不知道)。我需要每个键都有两个值。

我目前的代码是:

 def combos(length, possibles):
   ret = []
   if length == 1:
     return list(possibles) 
   else:
     subs = combos(length -1, possibles)
     ret = ret + subs
     for ch in possibles:
       for sub in subs:
         ret.append(str(ch) + str(sub))
   return ret

list = combos(2,"ab")
datasource = dict(enumerate(list))

我需要字典:

{0: 'a', 'foo', 1: 'b', 'foo', 2: 'aa', 'foo', 3: 'ab', 'foo', 4: 'ba', 'foo', 5: 'bb', 'foo'}

我正在创建所有这些组合以发送到散列组合的地图函数(为了便于比较,我截断到前五个位置)。我想比较mapfunction中的结果(5位)散列和我在命令行传递的参数(这是散列本身)。

1 个答案:

答案 0 :(得分:1)

from itertools import product

def myenumerate(length, possibles):
    for i in xrange(length):
        for r in product(possibles, repeat=i + 1):
            yield "".join(r)

print {
    i: [v, 'foo']
    for i, v in enumerate(myenumerate(2, "ab"))
}

结果:

{0: ['a', 'foo'], 1: ['b', 'foo'], 2: ['aa', 'foo'], 3: ['ab', 'foo'], 4: ['ba', 'foo'], 5: ['bb', 'foo']}
相关问题