Python直方图

时间:2015-01-08 21:27:00

标签: python python-3.x histogram

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

应该看起来像这样:

enter image description here

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

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"))

如何创建实际直方图?

2 个答案:

答案 0 :(得分:2)

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

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

也就是说,你可以取一串4颗星(由'*'重复四次形成)并将它放在一个长度为10个字符的字符串中,与左边对齐(<)和用空格填充到右边。

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

答案 1 :(得分:0)

就像这样:

# 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     **********