使用Python中的类将字典转换为对象列表

时间:2013-10-09 19:24:22

标签: python list class dictionary

def calc (allWords):
    d = {}                          
    for word in allWords:           
        if word in d.keys():        
            d[word] = d[word] + 1     
        else:
            d[word] = 1
        print (word , d[word])

def retriveFile():
    FileObject = open ("a.txt")     
    data = FileObject.read()        
    abc = data.split()              
    calc(abc)                    
    return abc

retriveFile()

我正在尝试使用类

将字典转换为2个对象的列表

第一个对象必须有实例变量(字符串) 第二个对象必须具有单词数(int)

我似乎不明白我如何使用课程,但我开始是这样的:

class list:
    def __init__(self, words, antal):
        self.words = words
        self.antal = antal
    for words, antal in d.items()
        if words

1 个答案:

答案 0 :(得分:0)

我不是100%肯定我理解,但我认为你想要一个Counter

from collections import Counter

counter = Counter(allWords)
for word, count in counter.items():
    print word, count