2016-11-06 79 views
-1

我從一個文件製作一個直方圖,然後我得到它的工作,但它沒有正確排序它們。含義100 90 50等我的程序沒有正確排序

這裏是我的代碼:

from collections import Counter 
data=[] 
with open("data.txt", 'r') as f: 
    for line in f: 
    line = line.strip() 
    data.append(str(line)) 

counts = Counter(data) 

for key, size in sorted(counts.items()): 
    print('{}: {}'.format(key, int(size) * '*')) 

這是輸出:

100: ****** 
25: ** 
50: *** 
60: * 
65: * 
70: ** 
75: * 
80: **** 
85: **** 
90: *** 

任何建議?

編輯:

我的意思是,他們去按數字順序。因此,我想100,25,50,....我想100,90,85,.....

+0

看起來排序以我 – njzk2

+0

我的意思是,爲了數字上走。所以我想要100,25,50,....我要100,90,85,..... –

+0

你排序在元組上,元組的第一項是「key」,關鍵是字符串,這是一個字母順序。如果你想要一個數字順序,你需要將字符串解析爲一個數字。 – njzk2

回答

0

njzk2是絕對正確的,謝謝!你可以做到這一點 一種方法是這樣的:

... 
line = line.strip() 
# casting to 'int' type just before populating in data table.. 
data.append(int(line)) 
... 

然後,你可以

... 
# applying reversed to reorder from ascending order to descending order. 
for key, size in sorted(counts.items(), reverse=True): 
...