2015-05-04 49 views
1
infile = open('numbers.txt','r') 

c = 0 
for i in infile: 
    if int(i) > c: 
     c = int(i) 
hist = [0]*c 

for i in infile: #checking 
    ii = int (i)-1 
    hist[ii] += 1 # problem area seemingly 

for i in range(c): 
    print(str(i+1),':',end=' ') 
    print(str(hist[i])) 

上面的代碼的目的是打開number.txt,它有100個數字,都在範圍內(1,101),所有都在其末尾有'\ n'個字符,並且計算每個數字遇到的次數。遞增列表值Python 3

首先找到文件中最大的數字,然後用元素數量等於文件中最大的數字的列表是由最初設置爲零的所有元素組成的。然後檢查數字。文件中的所有數字都是整數。

如果包含在文件中的最大數是100,則該直方圖[]列表具有最初100個元素,其均爲0

在檢查,說如果遇到數78,具有索引元素[ 77],即hist [77]從值0更新爲1.如果再次遇到78,則hist [77]從1更改爲2.

這樣,無論文件中發生了多少個數字,計數器(也沒有出現的數字,但少於最大出現的數字有計數器但這不是問題)。

檢查到打開了正確的文件後,hist列表最初被正確設置,問題是當遇到相應的數字時,hist []列表的值不會增加。當我在最後打印列表時,所有值仍然爲零。

我正在使用Python 3.4.3。腳本和'numbers.txt'都在我的桌面上。任何幫助讚賞。

回答

1

您正在遍歷文件兩次,但沒有將文件讀指針倒回到開始位置。如果沒有seek迭代

infile.seek(0) 
for i in infile: #checking 

超過infile不會產生任何進一步的行;:第二循環之前添加file.seek()通話你到達文件末尾已經

你會更好使用collections.Counter() object雖然這裏:

from collections import Counter 

with open('numbers.txt','r') as infile: 
    hist = Counter(int(line) for line in infile) 

然後,您可以得到使用max(hist)或代替檢索最常見的數字與Counter.most_common()方法最小訂貨量最高的計數值:

# In numerical order, setting missing numbers to 0 
for i in range(1, max(hist) + 1): 
    print('{}: {}'.format(i, hist.get(i, 0))) 

# In most common to least order 
# In numerical order 
for number, count in hist.most_common(): 
    print('{}: {}'.format(number, count)) 
+0

非常感謝。我有一種誤解,認爲只有像read(),readline()這樣的方法纔會提高文件指針,而不是像infile中的基於語法的語句:我是一個python新手,所以......無論如何再次感謝。 – user2873330