我剛剛通過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,並會喜歡提示。謝謝。
謝謝你的解釋。我做了改變,一切都很好。我很感激。 –