繁体   English   中英

将字典中的字符与字符串进行比较,删除 dic 项并将修改后的 dic 作为字符串返回

[英]Compare characters in a dictionary to a string, remove the dic item and return the modified dic as a string

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM