2017-04-18 62 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是一个字典,是在计数的东西特别好只是一个特例。使用键值对正是你解决这个问题的方法。任何其他解决方案都是人为和愚蠢的。