2016-01-24 92 views
1

我剛剛通過Python文檔,教程和SO問題開始自學Python。爲什麼設置不計算我的唯一整數?

到目前爲止,我可以要求用戶輸入文件,打開並讀取文件,刪除文件中的所有#並開始\ n,將每行讀入數組,並計算每行的整數數量。

我想計算每行唯一整數的數量。我意識到Python使用了一套我認爲完美的計算功能。但是,我總是會收到比先前值更大的值(我會告訴你)。我查看了其他與SOT相關的SO帖子,並沒有看到我沒有失蹤並且被困了一段時間。

下面是代碼:

with open(filename, 'r') as file: 
    for line in file: 
     if line.strip() and not line.startswith("#"): 
      #calculate the number of integers per line 
      names_list.append(line) 
      #print "There are ", len(line.split()), " numbers on this line" 

      #print names_list 

      #calculate the number of unique integers 
      myset = set(names_list) 
      print myset 
      myset_count = len(myset) 
      print "unique:",myset_count 

爲了進一步說明:

names_list是:

['1 2 3 4 5 6 5 4 5\n', '14 62 48 14\n', '1 3 5 7 9\n', '123 456 789 1234 5678\n', '34 34 34 34 34\n', '1\n', '1 2 2 2 2 2 3 3 4 4 4 4 5 5 6 7 7 7 1 1\n'] 

和my_set是:

set(['1 2 3 4 5 6 5 4 5\n', '1 3 5 7 9\n', '34 34 34 34 34\n', '14 62 48 14\n', '1\n', '1 2 2 2 2 2 3 3 4 4 4 4 5 5 6 7 7 7 1 1\n', '123 456 789 1234 5678\n']) 

我接收的輸出是:

unique: 1 
unique: 2 
unique: 3 
unique: 4 
unique: 5 
unique: 6 
unique: 7 

應該發生的輸出是:

unique: 6 
unique: 3 
unique: 5 
unique: 5 
unique: 1 
unique: 1 
unique: 7 

任何建議,爲什麼每行我的設置是不是計算每行的唯一整數的是否正確?我還想就如何改進我的代碼提出一些建議(如果您願意),因爲我昨晚自己開始學習Python,並會喜歡提示。謝謝。

回答

3

的問題是,因爲你是遍歷文件要附加的每一行列表names_list。之後,你從這些行中構建一個集合。您的文本文件似乎沒有任何重複行,因此,打印您設置的長度僅顯示當前處理的行數。

這裏有一個評論修復:

with open(filename, 'r') as file: 
    for line in file: 
     if line.strip() and not line.startswith("#"): 
      numbers = line.split() # splits the string by whitespace and gives you a list 
      unique_numbers = set(numbers) # builds a set of the strings in numbers 
      print(len(unique_numbers)) # prints number of items in the set 

注意,我們使用的是當前處理線,並建立由它的集合(分割線後)。您的原始代碼存儲所有行,然後根據每個循環中的行建立一個集合。

+0

謝謝你的解釋。我做了改變,一切都很好。我很感激。 –

2
myset = set(names_list) 

應該

myset = set(line.split()) 
+0

謝謝。我很感激。 –

相關問題