假设我想创建一个列表的箱线图,其中包含数字 1-5 大约一百万次。
这样的列表的大小约为 5 000 000,但表示为 dict 它根本不占用空间:
s = {1: 1000000, 2: 1000000, 3: 1000000, 4: 1000000, 5:1000000}
问题是,如果我尝试创建该字典的箱线图,我会收到错误
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
ax.boxplot(s)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/matplotlib/axes.py", line 5462, in boxplot
if not hasattr(x[0], '__len__'):
KeyError: 0
有没有一种巧妙的方法来绘制字典s
,而不必将所有元素放在一个列表中?
一条评论建议我试试
boxplot(n for n, count in s.iteritems() for _ in xrange(count))
但这导致
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
boxplot(n for n, count in s.iteritems() for _ in xrange(count))
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2134, in boxplot
ret = ax.boxplot(x, notch, sym, vert, whis, positions, widths, patch_artist, bootstrap)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/site-packages/matplotlib/axes.py", line 5462, in boxplot
if not hasattr(x[0], '__len__'):
TypeError: 'generator' object has no attribute '__getitem__'