【问题标题】:Compare characters in a dictionary to a string, remove the dic item and return the modified dic as a string将字典中的字符与字符串进行比较,删除 dic 项并将修改后的 dic 作为字符串返回
【发布时间】:2019-08-07 10:14:27
【问题描述】:

我有一个函数,它接受一个字符串参数,然后将其转换为直方图字典。该函数应该做的是将作为字符的每个键与包含字母表中所有字母的全局变量进行比较。返回一个新字符串,其中字母减去字典中的字符。我将如何在使用 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")

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

提前致谢。

【问题讨论】:

  • 太好了。功能在哪里?您面临哪些问题?请给minimal reproducible example
  • 也许this 会给你一个想法。考虑使用来自collecitons 模块的Counter 对象,因为它非常适合您的应用程序。编辑:链接修复

标签: python string dictionary histogram


【解决方案1】:

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

【讨论】:

  • 谢谢,我修改了一些东西并在输入参数上使用了 list() 并将字母表放在直方图中。现在一切正常,感谢您的帮助和列表建议。
猜你喜欢
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2020-03-23
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多