如何在用户已经输入了键的字典中添加值?

2024-05-18 14:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这将是我目前正在做的练习:编写一个函数distinct_characters,以获取字符串列表作为参数。它应该返回一个字典,其键是输入列表的字符串,相应的值是键中不同字符的数量

解决方案:{“检查”:4,“查看”:3,“尝试”:3,“弹出”:2}

我的代码:

    def distinct_characters(l):
            dictOfWords = {i: 5 for i in l}
            for key in dictOfWords:
            keys = (len(set(key[0:len(dictOfWords)])))
         print(dictOfWords)

    distinct_characters(["check", "look", "try", "pop", "obo", "hehe"])

输出:{'check':5,'look':5,'try':5,'pop':5,'obo':5,'hehe':5}

我尝试了for循环,没有使用key,但是我没有返回字典的通常格式

    def distinct_characters(l):
         dictOfWords = {i: 5 for i in l}
         for i in dictOfWords:
            print(len(set(i[0:len(dictOfWords)])), i, end=" ")

distinct_characters(["check", "look", "try", "pop", "obo", "hehe"])

Output: 4 check 3 look 3 try 2 pop 2 obo 2 hehe


Tags: key字符串in列表forlencheckpop
3条回答

需要注意的是,在创建原始dictOfWords之后,您永远不会修改它。另外,当您创建字典时,您会为每个用作键的单词分配一个值5

您可以通过以下方式使用dict理解以pythonic方式完成此任务:

def disctinct_characters(listofwords):
    return {word: len(set(word)) for word in listofwords}

def distinct_characters(l):
    d=dict()
    for i in l:
        k = set(i)
        d[i] = len(k)
    return d
distinct_characters(["check", "look", "try", "pop", "obo", "hehe"])

这就行了

下面的代码段应该可以工作

from collections import defaultdict

def distinct_characters(l):
    result = {}
    for each in l:
        temp = defaultdict(int)
        for char in each:
            temp[char] += 1
        result[each] = len(temp)

    return result

print(distinct_characters(["check", "look", "try", "pop", "obo", "hehe"]))

我使用defaultdict来避免键错误。基本上,它与默认的python字典相同

相关问题 更多 >

    热门问题