【问题标题】:troubles with dictionaries, python [closed]字典的麻烦,python [关闭]
【发布时间】: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


【解决方案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]

【讨论】:

    【解决方案2】:

    如果您在处理某些代码时遇到问题,则应始终尝试将实际代码放在一边,并考虑算法:也就是说,它在伪代码甚至纯英语中的实际工作方式。在这种情况下,它将如下所示:

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

    这样的话,它并不太复杂,所以你应该可以编码。

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

    【讨论】:

    • 这在迭代时从字典中删除项目有点困难。
    • 不是这样。当你遍历字典的键时,你会得到一个副本,当你从字典中删除项目时它不会改变。见the documentation
    • 哦,是的。我正在考虑迭代字典本身,从而产生键。迭代 d.keys()(或 Python 3 中的 list(d.keys()))应该可以工作。
    【解决方案3】:

    试试这个

    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]: 设置(['hi', 'foo'])

    【讨论】:

      猜你喜欢
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多