python - 在 python 循环中修改字典
问题描述
我试图通过将每个事件添加到字典中来计算某些文本中的字母数量,然后在需要时添加它。但是,字典最后显示为空白。我究竟做错了什么?
text = "test 1234!"
dic = {}
for char in text:
for key, value in dic:
if key == char:
value = value + 1
else:
dic[char] = 1
print(dic)
谢谢
解决方案
无需遍历 dict,您只需检查密钥是否char
已存在:
dic = {}
for char in text:
if char in dic:
dic[char] += 1
else:
dic[char] = 1
print(dic)
# Out: {'t': 2, 'e': 1, 's': 1, ' ': 1, '1': 1, '2': 1, '3': 1, '4': 1, '!': 1}
除了自己编写之外,您还可以使用已实现的模块来执行此类操作。一个选项Counter
来自collections
模块,它也将返回一个dict
:
from collections import Counter
counts = Counter(text)
print(counts)
# Out: Counter({'t': 2,
# 'e': 1,
# 's': 1,
# ' ': 1,
# '1': 1,
# '2': 1,
# '3': 1,
# '4': 1,
# '!': 1})
推荐阅读
- c# - Xamarin Crashlytics
- c++ - 使用 putText 和 FreeFontStyle 在 opencv 中绘制希腊符号
- java - SQL 错误或缺少数据库(“(”附近:语法错误)
- c - 当它们之间有一个字符串时如何从文件中读取多个整数
- reactjs - 无法通过变量路径/:id获取道具,反应路由器dom
- android - 这两个版本有和没有“-k419”有什么区别?
- python - 在三个骰子的列表中滚动两个骰子时找到最大值
- javascript - 无法在模式中输入文本框并使用新状态重新渲染
- python - 使用 seaborn 创建分组条形图
- python - 如何读取 csv,在 python 中获取最大列?