2017-04-22 27 views
1

我在字典中具有特定的值,可以從高到低排序,但可以有多達一千或更多的值。如果一個數字在1-10之間,並且在圖表中輸出一個圖表的前1-10個最高值,那麼如何處理用戶輸入。所以,如果他們輸入3,將繪製在先進如何根據用戶輸入將從字典中的值從最高值降到最低值

from collections import Counter 
from scipy import * 
from matplotlib.pyplot import * 
import matplotlib.pyplot as plot 


frequency1 = Counter({'1':100,'2':400,'3':200,'4':300,}) 



response1 = input("How many top domains from source? Enter a number between 1-10: ") 

if response1 == "1":   
    if len(frequency1) >= 1: 

     print("\nTop 1 most is:") 
     for key, frequency1_value in frequency1.most_common(1): 
       print("\nNumber:",key,"with frequency:",frequency1_value) 

       ########Graph for this output 

       x = [1,2] 
       y = [frequency1_value,0] 

       figure(1) 

       ax = plot.subplot(111) 
       ax.bar(x,y,align='center', width=0.2, color = 'm') 


       ax.set_xticklabels(['0', '1']) 
       xlabel("This graph shows amount of protocols used") 
       ylabel("Number of times used") 
       grid('on')  


################################## END GRAPH 
    else: 
     print("\nThere are not enough domains for this top amount.") 

if response1 == "2":   
    if len(frequency1) >= 2: 
     print("\nTop 2 most is:") 
     for key, frequency1_value in frequency1.most_common(2): 
       print("\nNumber:",key,"with frequency:",frequency1_value) 

       ########Graph for this output 

       x = [1,2,3] 
       y = [frequency1_value,frequency1_value,0] 

       figure(1) 

       ax = plot.subplot(111) 
       ax.bar(x,y,align='center', width=0.2, color = 'm') 


       ax.set_xticklabels(['0', '1','','2']) 
       xlabel("This graph shows amount of protocols used") 
       ylabel("Number of times used") 
       grid('on')  


################################## END GRAPH 

    else: 
     print("\nThere are not enough domains for this top amount.") 

回答

1

代碼中的3個最高值等等...謝謝下面將創建在字典中值的排序列表,然後繪製的最大對應的圖數字,取決於用戶輸入。

import numpy as np 
import matplotlib.pyplot as plt 

d = {'1':100,'2':400,'3':200,'4':300,} 

vals = sorted(d.values(), reverse=True) 

response = input("How many top domains from source? Enter a number between 1-10: ") 

if response > 0 and response < len(vals)+1: 

    y = vals[:response] 

    print ("\nTop %i most are:" %response) 
    print (y) 

    x = np.arange(1,len(y)+1,1) 

    fig, ax = plt.subplots() 

    ax.bar(x,y,align='center', width=0.2, color = 'm') 

    ax.set_xticks(x) 
    ax.set_xticklabels(x) 
    ax.set_xlabel("This graph shows amount of protocols used") 
    ax.set_ylabel("Number of times used") 
    ax.grid('on') 
else: 
    print ("\nThere are not enough domains for this top amount.") 

plt.show() 

例如,如果用戶輸入3到代碼,下圖將與輸出端產生:

Top 3 most are: 
[400, 300, 200] 

enter image description here

+0

感謝您的響應!這是否適用於python 3.5?我得到一個錯誤在第19行str()> int()。 – k5man001

+0

其實我得到它,輸入需要被轉換爲int ..感謝您的幫助! – k5man001

相關問題