【发布时间】:2014-02-07 21:28:17
【问题描述】:
我正在创建一个类来使用 .txt 文件进行练习。我对如何在我的课堂上实现某个方法有点困惑。我的班级如下:
class Collection_of_word_counts():
'''this class has one instance variable, called counts which stores a dictionary
where the keys are words and the values are their occurences'''
def __init__(self:'Collection_of_words', file_name: str) -> None:
''' this initializer will read in the words from the file,
and store them in self.counts'''
l_words = open(file_name).read().split()
s_words = set(l_words)
self.counts = dict([ [word, l_words.count(word)]
for word
in s_words])
现在,我的一种方法将比较两个字典并删除它们都包含相同作品或者更确切地说是键的任何出现。这就是我迄今为止所拥有的,未完成的,我很确定我完全错了。我想指导如何像程序员一样思考如何实现这种方法。字典就在我头上。我是新手。
def compare_coll(self,coll_1, coll_2) -> None:
''' compares two collections of key words which are dictionaries,
<coll_1> and <coll_2>, and removes from both collections every word
that appears in b oth collection'''
while d1.contains(d2.keys) and d2.contains(d1.keys):
【问题讨论】:
-
您能否举一些输入示例以及您对这些输入的期望输出?它们应该是非常简短的示例,例如:
d1 = {'abc':3, 'abcd':2, 'foo':1}.
标签: python class methods dictionary