2017-04-18 25 views
-4

我有這種格式的文本文件,其中:在python中使用字典的替代方法?

SA:MC:1:1 
UR:SA:0:0 
KR:GE:2:0 
AR:KR:1:0 

和我的代碼計算在文本文件中的隊名的發生給我的輸出這樣的數字:

SA: 2 
MC: 1 
UR: 1 
KR: 2 
AR: 1 

代碼:

fileName = input("Enter the name of file:") 
game = open(fileName) 
table = [] 

for line in game: 
contents = line.strip().split(':') 
table.append(contents[:-2]) 

dictionary = {} 
for line in table: 
    for country in line: 
     if country in dictionary: 
      dictionary[country] += 1 
     else: 
      dictionary[country] = 1 

for country, occurences in dictionary.items(): 
    print(country, ':', occurrences) 

該代碼的作品,並給我所需的輸出,因爲我查看字典術語,它使這種任務更容易。但是,我想知道是否有其他選擇,而不是使用字典?更多的一個手動方式這樣做的首發

+4

不是。你爲什麼想要更「手動的方式」? – Ryan

+2

做關鍵價值商店的Pythonic方式是使用字典。你有沒有充分的理由不使用它們,或者你只是出於好奇而問? –

+1

您可以推出自己的[紅黑樹](https://en.wikipedia.org/wiki/Red-black_tree)實現,並在其上構建一個鍵值存儲,但它可能會比無論如何都要使用字典。 –

回答

0

你可以做到這一點減去使用collections.Counter的手動方式。

from collections import Counter 

c = Counter() 

with open(filename) as f: 
    for line in f: 
     a, b, _, _ = line.split(":") 
     c += Counter([a, b]) 

但是千萬注意,collections.Counter是一個字典,是在計數的東西特別好只是一個特例。使用鍵值對正是你解決這個問題的方法。任何其他解決方案都是人爲和愚蠢的。