用python 3打印直方图
我有一个单词长度的单词重复字典,我想做一个直方图,就像下面链接中的一样,只使用python内置函数no numpy或类似的东西用python 3打印直方图,python,python-3.x,histogram,Python,Python 3.x,Histogram,我有一个单词长度的单词重复字典,我想做一个直方图,就像下面链接中的一样,只使用python内置函数no numpy或类似的东西 请至少帮我一些指点。我想你一定有一个类似于这个的dict,对吗 >>> d = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1} >>> d {1: 1, 2: 10, 3: 10, 4: 6, 5: 5, 6: 4, 7: 2, 8: 1} 如果是这样的话,我有一个函数可以做到这一点: >
请至少帮我一些指点。我想你一定有一个类似于这个的
dict
,对吗
>>> d = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1}
>>> d
{1: 1, 2: 10, 3: 10, 4: 6, 5: 5, 6: 4, 7: 2, 8: 1}
如果是这样的话,我有一个函数可以做到这一点:
>>> def histo(dict_words):
# Get max values, plus delta to ease display
x_max = max(dict_words.keys()) + 2
y_max = max(dict_words.values()) + 2
# print line per line
print '^'
for j in range(y_max, 0, -1):
s = '|'
for i in range(1, x_max):
if i in dict_words.keys() and dict_words[i] >= j:
s += '***'
else:
s += ' '
print s
# print x axis
s = '+'
for i in range(1, x_max):
s += '---'
s += '>'
print s
# print indexes
s = ' '
for i in range(1, x_max):
s += ' %d ' % i
print s
>>> histo(d)
^
|
|
| ******
| ******
| ******
| ******
| *********
| ************
| ***************
| ***************
| ******************
|************************
+--------------------------->
1 2 3 4 5 6 7 8 9
>>>
好的,在左边显示值和正确设置大于10的数字格式方面还有一些工作要做,以避免索引发生移位,但我认为这是一个好的开始:-)您至少需要提供一个输入和预期输出的示例。比如,字典中的5个条目和相应的柱状图。您可能应该提到这是Oreilly的Python 1课程期末考试的一部分