词典理解和创建过程中的关键字检查

2024-09-24 22:17:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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将包括启动理解的范围内的所有内容,这会使事情变得更困难。在


Tags: 文件方法代码inwith密钥open字符
3条回答

在python2.7中,您可以使用^{}

from collections import Counter

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

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

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

使用defaultdict:

from collections import defaultdict

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

如果您真的想使用列表理解,可以使用这种效率低下的变体:

^{pr2}$

相关问题 更多 >