【问题标题】:Dictionary comprehension and checking for keys during creation在创建过程中字典理解和检查键
【发布时间】:2011-03-17 09:29:17
【问题描述】:

我的任务是读取文件,将每个字符作为键存储在字典中,并为每个找到的键增加值,这导致代码如下:

chrDict = {}
with open("gibrish.txt", 'r') as file:
    for char in file.read():
        if char not in chrDict:
            chrDict[char] = 1
        else:
            chrDict[char] += 1

所以这行得通,但对我来说,至少在 Python 中,这看起来真的很难看。我尝试了不同的理解方式。有没有办法通过理解来做到这一点?我在创建过程中尝试使用 locals() ,但这似乎真的很慢,而且如果我正确理解了任何内容,locals 会将所有内容都包含在启动理解的范围内,这会使事情变得更加困难。

【问题讨论】:

    标签: python dictionary list-comprehension


    【解决方案1】:

    Python 2.7中,您可以使用Counter

    from collections import Counter
    
    with open("gibrish.txt", 'r') as file:
        chrDict = Counter(f.read())
    

    【讨论】:

    【解决方案2】:

    使用默认字典:

    from collections import defaultdict
    
    chr_dict = defaultdict(int)
    with open("gibrish.txt", 'r') as file:
        for char in file.read():
            chr_dict[char] += 1
    

    如果你真的想使用列表推导,你可以使用这个低效的变体:

    text = open("gibrish.txt", "r").read()
    chr_dict = dict((x, text.count(x)) for x in set(text))
    

    【讨论】:

      【解决方案3】:

      Dictionary get() 方法将返回该值,如果存在,则返回 0。

      chrDict = {}
      with open("gibrish.txt", 'r') as file:
         for char in file.read():
              chrDict[char] = chrDict.get(char, 0) + 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-28
        • 2011-12-20
        • 1970-01-01
        • 2018-07-28
        • 2021-10-25
        • 1970-01-01
        • 2013-11-01
        相关资源
        最近更新 更多