字典麻烦,蟒蛇

时间:2014-02-07 21:28:18

标签: python class methods dictionary

我正在创建一个类来处理.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):

3 个答案:

答案 0 :(得分:1)

  

现在,我的一个方法将比较两个词典并删除它们都包含相同工作的任何事件,或者更确切地说是键。

这对设置操作来说非常简单:

def compare_coll(self, coll_1, coll_2):
    # get list of keys which exist in both dicts
    overlap = set(coll_1).intersection(coll_2)
    # delete these keys from both dicts
    for key in overlap:
        del coll_1[key], coll_2[key]

答案 1 :(得分:0)

如果你遇到一些代码问题,你应该总是试着不考虑实际的代码并考虑算法:也就是说,它实际上如何在伪代码甚至简单的英语中工作。在这种情况下,它将如下:

Go through every key in the first dict.
For each one, does it exist in the second dict?
If so, remove it from both.

当这样说时,它并不太复杂,所以你应该能够对它进行编码。

(顺便说一下,有一个使用集合的单行实现。暂时不要担心。)

答案 2 :(得分:0)

试试这个

def compare_coll(self,coll_1, coll_2)

    set1 = set(coll_1)
    set2 = set(coll_2)
    return set1 - set2

这是ipython的输出

在[6]中:list1 = ['bar','foo','hello','hi']

在[7]中:list2 = ['alpha','bar','hello','xam']

在[8]中:

在[8]中:set1 = set(list1)

在[9]中:set2 = set(list2)

在[10]中:set1 - set2 Out [10]:set(['hi','foo'])