所以这是我的字典片段,我需要帮助创建一个新的字典,它基本上是一个直方图,其中键是元素的数量,而值是旧字典中的键。
e.g。 1: [27,31]
23: ['20', '10', '3'],
24: ['19', '16', '14', '6'],
25: ['16', '5', '9', '24', '18', '15', '11', '12', '14', '5'],
26: ['22', '15', '10', '6', '5', '4'],
27: ['4'],
28: ['27', '26', '20', '9', '22', '9', '25', '7'],
29: ['15', '26', '16', '24', '4'],
30: ['25', '16', '18', '21', '19', '4'],
31: ['2'],
答案 0 :(得分:2)
标准技巧是使用defaultdict
进行这种直方图编码:
In [8]: d = {23: ['20', '10', '3'],
...: 24: ['19', '16', '14', '6'],
...: 25: ['16', '5', '9', '24', '18', '15', '11', '12', '14', '5'],
...: 26: ['22', '15', '10', '6', '5', '4'],
...: 27: ['4'],
...: 28: ['27', '26', '20', '9', '22', '9', '25', '7'],
...: 29: ['15', '26', '16', '24', '4'],
...: 30: ['25', '16', '18', '21', '19', '4'],
...: 31: ['2'],}
In [9]: from collections import defaultdict
In [10]: hist = defaultdict(list)
In [11]: for k,v in d.iteritems():
...: hist[len(v)].append(k)
In [12]: hist
Out[12]: defaultdict(<type 'list'>, {1: [27, 31], 3: [23], 4: [24],
5: [29], 6: [26, 30], 8: [28], 10: [25]})
答案 1 :(得分:0)
我认为这个想法应该是:
keys = olddic.getallkeys() //which get all the keys
declare newdic={};
iterate each of key in the olddic{
array = olddic[eachkey]
newkey = array.size //the length/size
store newkey:array into newdic
}
我为你编写了绒面革代码,但我认为编写实际代码是你的工作。
使用matplotlib库创建直方图将节省您的日子!