Skip to main content
 首页 » 编程设计

python之使用defaultdict的解决方案和使用setdefault的解决方案有什么区别

2024年10月01日8lvdongjie

在 Think Python 中,作者介绍了 defaultdict。以下是关于defaultdict 的书的摘录:

If you are making a dictionary of lists, you can often write simpler code using defaultdict. In my solution to Exercise 12-2, which you can get from http://thinkpython2.com/code/anagram_sets.py, I make a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters. For example, 'opst' maps to the list ['opts', 'post', 'pots', 'spot', 'stop', 'tops']. Here’s the original code:

 def all_anagrams(filename): 
     d = {} 
     for line in open(filename): 
         word = line.strip().lower() 
         t = signature(word) 
         if t not in d: 
             d[t] = [word] 
         else: 
             d[t].append(word) return d 

This can be simplified using setdefault, which you might have used in Exercise 11-2:

 def all_anagrams(filename): 
     d = {} 
     for line in open(filename): 
         word = line.strip().lower() 
         t = signature(word) 
         d.setdefault(t, []).append(word)  
     return d 

This solution has the drawback that it makes a new list every time, regardless of whether it is needed. For lists, that’s no big deal, but if the factory function is complicated, it might be. We can avoid this problem and simplify the code using a defaultdict:

def all_anagrams(filename): 
    d = defaultdict(list) 
    for line in open(filename): 
        word = line.strip().lower() 
        t = signature(word) 
        d[t].append(word) 
    return d 

下面是signature函数的定义:

def signature(s): 
    """Returns the signature of this string. 
 
    Signature is a string that contains all of the letters in order. 
 
    s: string 
    """ 
    # TODO: rewrite using sorted() 
    t = list(s) 
    t.sort() 
    t = ''.join(t) 
    return t 

关于第二种解决方案,我的理解是 setdefault 检查 t (单词的签名)是否作为键存在,如果不存在,则将其设置为key 并设置一个空列表作为它的值,然后 append 将这个词附加到它上面。如果t存在,setdefault返回它的值(一个至少有一项的列表,它是一个代表单词的字符串),append追加此列表中的单词。

我对第三种解决方案的理解是,d 表示 defaultdict,它使 t 成为键并将空列表设置为它的值(如果 t 还不作为键存在),那么该词将附加到列表中。如果 t 确实已经存在,则返回其值(列表),并在其后附加单词。

第二种方案和第三种方案有什么区别?我这是什么意思,无论是否需要,第二个解决方案中的代码每次都会创建一个新列表? setdefault 如何对此负责?使用 defaultdict 如何让我们避免这个问题?第二种和第三种解决方案有何不同?

请您参考如下方法:

“每次都创建一个新列表”意味着每次调用 setdefault(t, []) 时,一个新的空 list([] 参数)被创建为默认值以防万一需要它。使用 defaultdict 可以避免这样做。

虽然这两种解决方案都返回字典,但使用 defaultdict 的解决方案实际上返回的是 defaultdict(list),它是内置 dict< 的子类类。这通常不是问题。最显着的效果可能是 print() 返回的对象,因为两者的输出看起来完全不同。

如果您出于某种原因不想这样做,可以将函数的最后一条语句更改为:

    return dict(d) 

将创建的 defaultdict(list) 转换为常规 dict。