【问题标题】:Print histogram in python 3在python 3中打印直方图
【发布时间】:2011-06-15 15:21:43
【问题描述】:

我有一个单词 length_of_word |重复字典,我想制作一个直方图,就像下面链接中的直方图一样,只使用 python 内置函数,没有 numpy 或类似的东西。

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

请至少给我一些建议。

【问题讨论】:

  • 您至少必须提供一个输入示例和预期输出。比如说,字典中的 5 个条目和相应的直方图。
  • 您可能应该提到这是 Oreilly 的 Python 1 课程的期末考试的一部分。 :)

标签: python python-3.x histogram


【解决方案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 的数字以不改变索引,还有一些工作要做,但我认为这是一个好的开始 :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多