1

所以这是我字典的一个片段,我需要帮助创建一个新字典,它基本上是一个直方图,其中键是元素的数量,值是旧字典中的键。

例如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'],
4

2 回答 2

2

一个标准技巧是使用 adefaultdict进行这种直方图:

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]})
于 2013-10-13T18:39:19.150 回答
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 库创建直方图将节省您的时间!

http://matplotlib.org/

于 2013-10-13T18:41:41.783 回答