用Python 3打印直方图

2 投票
1 回答
2758 浏览
提问于 2025-04-16 10:38

我有一个字典,里面记录了单词的长度和出现次数,我想用Python内置的函数来制作一个像下面链接中的直方图,不想用numpy或者其他类似的库。

http://dev.collabshot.com/show/723400/

请帮帮我,至少给我一些建议。

1 个回答

3

我猜你应该有一个像这样的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的数字需要多做一点工作,以免索引错位,但我觉得这已经是个不错的开始了 :-)

撰写回答