python - 将字典中的字符与字符串进行比较,删除 dic 项并将修改后的 dic 作为字符串返回
问题描述
我有一个接受字符串参数的函数,然后将其转换为直方图字典。该函数应该做的是将作为字符的每个键与包含字母表中所有字母的全局变量进行比较。返回一个新字符串,其中字母减去字典中的字符。我将如何在使用 for 循环而不使用计数器的函数中完成此操作?
alphabet = 'abcdefghi'
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def missing_characters(s):
h = histogram(s)
global alphabet
for c in h.keys():
if c in alphabet:
del h[c]
missing_characters("abc")
我收到一条错误消息,指出字典已更改。我需要做的是从字典直方图中删除给定的字符串字符,并按顺序返回一个新字符串,其中除了作为参数传递的字符串中的字母之外的所有字母。
提前致谢。
解决方案
问题是 - 在 python3 中dict.keys()
产生了对键的迭代器。您可以list()
改用以下方法来解决此问题:
alphabet = 'abcdefghi'
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
def missing_characters(s):
h = histogram(s)
global alphabet
for c in list(h):
if c in alphabet:
del h[c]
missing_characters("abc")
推荐阅读
- sql-server - 以指数格式存储在 varchar 列中的数字
- python - 奇怪的行为:“12 in [12,13,14] == True”在 Python 中是什么意思
- c# - MSSQL 连接失败,登录凭据正确
- python - 在 Python 中使用 Selenium 时是否可以有多个显式等待?
- python - 使用beautifulsoup查找没有标签的json对象
- c++ - OpenSSL C API 解密有时不起作用
- c++ - 我必须在 C++ 的头文件中定义类吗?
- reactjs - 在 React 中创建共享身份验证 cookie
- python-3.x - ModuleNotFoundError:没有名为“tensorflow.experimental.numpy”的模块
- oracle - Oracle 数据库中的存储过程 (11g)