【问题标题】:Making bar chart from list从列表制作条形图
【发布时间】:2017-02-12 19:08:47
【问题描述】:

卡住了这个问题。我有列表[6,7,7,8,10]。我需要制作如下图。

 6 *
 7 **
 8 *
 9 
10 *

【问题讨论】:

  • 值是否排序?你自己的尝试是什么?

标签: python list diagram


【解决方案1】:

如果列表已排序并且您只想要从第一个到最后一个数字的图表。

a = [6, 7, 7, 8, 10]
for i in range(a[0], a[-1] + 1):
    print(i, sum([ k==i for k in a])*'*')

为了在未排序列表上工作,将 a[0] 替换为 min(a)a[-1] 替换为 max(a)

如果您不想打印零条目,请将 range 对象替换为 sorted(set(a))

【讨论】:

    【解决方案2】:
    data = [6, 7, 7, 8, 10] 
    
    for item in range(min(data), max(data) + 1):
        print item, data.count(item) * '*'
    

    输出:

    6 *
    7 **
    8 *
    9
    10 *
    

    【讨论】:

      【解决方案3】:

      这也应该适用于未排序的列表:

      l = [6,7,7,8,10]
      
      for i in range(min(l), max(l) + 1):
        print("%d: %s " % (i, '*' * l.count(i)))
      

      输出:

      6: * 
      7: ** 
      8: * 
      9:  
      10: *
      

      试试here!

      【讨论】:

        【解决方案4】:

        您可以使用字典来完成这项任务;

        a=input()
        d={}
        # this function is used to generate the dictionary for your hitogram
        def histogram(a):
            for i in a:
                try:
                    d[i]=d.get(i)+1
                except:
                    d[i]=1
        # to display the histogram
        def display(d):
            x=d.keys()
            x.sort()
            for i in x:
                print i,'*'*d[i]
        

        现在检查执行时间:

        import time
        t=time.time()
        a=[6,7,7,8,10]
        d={}
        def histogram():
            for i in a:
                try:
                    d[i]=d.get(i)+1
                except:
                    d[i]=1
        histogram()
        t1=time.time()
        print t1-t
        
        >>> 4.6968460083e-05
        

        【讨论】:

          猜你喜欢
          • 2022-10-07
          • 1970-01-01
          • 1970-01-01
          • 2017-04-18
          • 2014-03-31
          • 2021-06-10
          • 2013-06-16
          • 2013-09-13
          • 2021-09-30
          相关资源
          最近更新 更多