亲宝软件园·资讯

展开

python defaultdict()初始化

m0_46483236 人气:0

用法讲解:

dict =defaultdict(factory_function)
from collections import defaultdict
dict1 = defaultdict(int)  # dict1[1]=0
dict2 = defaultdict(set)  # dict2[1]=set()
dict3 = defaultdict(str)  # dict3[1]=
dict4 = defaultdict(list) # dict4[1]=[

应用举例: 题目描述:

1. 不使用defaultdict(): 

def isAnagram(s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    dict_s = {}
    for item in s:
        if item not in dict_s.keys():
            dict_s[item] = 1
        else:
            dict_s[item] += 1
    dict_t = {}
    for item in t:
        if item not in dict_t.keys():
            dict_t[item] = 1
        else:
            dict_t[item] += 1
    return dict_s == dict_t

2. 使用defaultdict(): 

def isAnagram(self, s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    from collections import defaultdict
    dict_s = defaultdict(int)
    dict_t = defaultdict(int)
    for item in s:
        dict_s[item] += 1
    for item in t:
        dict_t[item] += 1
    return dict_s == dict_t

参考:https://www.jianshu.com/p/bbd258f99fd3 

加载全部内容

相关教程
猜你喜欢
用户评论