首页 > 解决方案 > 将字典中的字符与字符串进行比较,删除 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")

我收到一条错误消息,指出字典已更改。我需要做的是从字典直方图中删除给定的字符串字符,并按顺序返回一个新字符串,其中除了作为参数传递的字符串中的字母之外的所有字母。

提前致谢。

标签: pythonstringdictionaryhistogram

解决方案


问题是 - 在 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")

推荐阅读