【问题标题】:Python HistogramPython直方图
【发布时间】:2015-03-07 03:20:24
【问题描述】:

我正在尝试在 python 中创建一个直方图,作为我的python 类的一部分

它应该是这样的:

但是,我无法弄清楚直方图。到目前为止,这是我的代码:

sumValues = [] 

print("Enter 10 integers")

for i in range( 10 ):
    newValue = int( input("Enter integer %d: " % (i + 1) ))
    sumValues.append(newValue)

print("\nCreating a histogram from values: ")
print("%s %10s %10s" %("Element", "Value", "Histogram"))

如何创建实际的直方图?

【问题讨论】:

  • 您所显示的不是正确的“直方图”(例如参见en.wikipedia.org/wiki/Histogram)。但是,这不会改变关于如何打印所显示内容的答案。

标签: python python-3.x histogram


【解决方案1】:

一些提示: 新型 Python 格式允许这样做:

In [1]: stars = '*' * 4    # '****'
In [2]: '{:<10s}'.format(stars)
Out[3]: '****      '

也就是说,你可以取一个 4 星的字符串(由 '*' 重复四次组成)并将它放在一个长度为 10 个字符的字符串中,左对齐 (&lt;) 并填充到右带空格。

(如果您不需要直方图具有相同数量的字符(星号或空格),只需打印星号即可;无需格式化)

【讨论】:

    【解决方案2】:

    就像这样:

    # fake data
    sumValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ...
    # calculate how long is the list and adjust the padding for 'Element'
    padding = max(len(sumValues), len('Element'))
    # now the padding for 'Value'
    padding1 = max(len(str(max(sumValues))), len('Value')) 
    
    print("\nCreating a histogram from values: ")
    print("%s %10s %10s" %("Element", "Value", "Histogram"))
    # use enumerate to loop your list and giving the index started from 1
    for i,n in enumerate(sumValues, start=1):
        print '{0} {1}     {2}'.format( # print each line with its elements
                  str(i).ljust(padding), # print with space using str.ljust
                  str(i).rjust(padding1), # print with space using str.rjust
                  '*'*n) # '*' * n = '*' multiply by 'n' times 
    
    Creating a histogram from values: 
    Element      Value  Histogram
    1              1     *
    2              2     **
    3              3     ***
    4              4     ****
    5              5     *****
    6              6     ******
    7              7     *******
    8              8     ********
    9              9     *********
    10            10     **********
    

    【讨论】:

      猜你喜欢
      • 2014-04-18
      • 2014-02-21
      • 1970-01-01
      • 2011-02-21
      • 2017-08-02
      • 2018-05-23
      • 2015-11-28
      • 1970-01-01
      相关资源
      最近更新 更多