我的任务是读取一个文件,将每个字符作为密钥存储在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将包括启动理解的范围内的所有内容,这会使事情变得更困难。在
在python2.7中,您可以使用^{} :
Dictionary get()方法将返回值(如果存在),否则返回0。在
使用defaultdict:
如果您真的想使用列表理解,可以使用这种效率低下的变体:
^{pr2}$相关问题 更多 >
编程相关推荐