2017-02-12 23 views
-2

卡住了這個問題。我有名單[6,7,7,8,10]。我需要製作如下圖。從列表中製作條形圖

6 * 
7 ** 
8 * 
9 
10 * 
+0

是值排序?你自己的嘗試是什麼? –

回答

0
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 * 
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])*'*') 

對於這個無序列表上工作由max(a)取代a[0]通過min(a)a[-1]

,如果你不希望打印的零項,與sorted(set(a))更換range對象。

0

這應該在無序列表藏漢工作:

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!

0

你可以用字典對於這項任務的工作;

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