從列表返回字典中的特定拆分字符串

H20zzz

這是我正在上課的一個練習。我將此發佈到留言板,得到的反饋表明我只使用姓名列表中的姓氏。最終,當它運行時,它只返回 {Marin:1} 而它應該返回一個包含所有名字作為鍵的字典,值是名稱在列表中出現的次數。任何和所有的幫助表示讚賞。

#Write a function called name_counts. name_counts will take
#as input a list of full names. Each name will be two words
#separated by a space, like "David Joyner".
#
#The function should return a dictionary. The keys to the
#dictionary will be the first names from the list, and the
#values should be the number of times that first name
#appeared.
#
#HINT: Use split() to split names into first and last.


#Add your function here!

    def name_counts(name_list):
        
        nameDict = {}
        for name in name_list:
            name = name.split()
            new_name = name[0]
        for first_name in new_name:
            if first_name in nameDict:
                nameDict[new_name]+=1
            else:
                nameDict[new_name]=1
        return nameDict

#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print (although the order of the keys may vary):
#{'Shelba': 5, 'Maren': 1, 'Nicol': 1, 'David': 2, 'Brenton': 2}

    name_list = ["David Joyner", "David Zuber", "Brenton Joyner",
                 "Brenton Zuber", "Nicol Barthel", "Shelba Barthel",
                 "Shelba Crowley", "Shelba Fernald", "Shelba Odle",
                 "Shelba Fry", "Maren Fry"]
    print(name_counts(name_list))
生鏽的Python

問題是兩個 for 循環。

for name in name_list:
            name = name.split()
            new_name = name[0]

第一個 for 循環遍歷名稱列表,拆分它們並將第一個名稱分配給 new_name 當 for 循環完成時, new_name 的值為“Maren”,它是列表中的最後一個名字。第二個 for 循環在第一個循環完成之前不會開始,因此它只知道 new_name 的值為“Maren”

.

for first_name in new_name:
            if first_name in nameDict:
                nameDict[new_name]+=1
            else:
                nameDict[new_name]=1

下一個 for 循環遍歷名稱“Maren”,它是一個字符串,因此一次一個字符執行,因為沒有字符“M”、“a”、“r”、“e”、“n”在字典默認為 else 子句,該子句每次將鍵“Maren”的值設置為 1。這就是你得到 {"Maren": 1} 的原因

刪除第二個 for 循環,只需檢查 new_name 是否在第一個 for 循環下的 nameDict 中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何拆分字典列表中的字典字符串值以添加新的字典项?

在包含字典的列表中查找特定字符串的计数

从字符串列表中的拆分字符串创建字典

從 Kotlin 中的列表或哈希映射數組列表拆分字符串

从列表中的子字符串返回与包含子字符串的字典的匹配值

如何从字典中搜索列表中的特定字符串并返回 mongodb 中包含该字符串的所有元素?

在嵌套列表中拆分字符串

拆分列表中的字符串

拆分列表字符串并创建字典

如何从列表中删除空字符串,该列表是字典列表中特定键的值?

拆分字符串中的特定文本

拆分字符串数组并将键值对存储在列表或字典中

从字典中删除特定字符串

從 Python 中的字符串中提取信息並返回列表

如何正确拆分字符串以在python中创建字典?

如何拆分二维字典中的字符串

拆分字典数组中的JSON字符串

根据字符串中的特定逗号有选择地将字符串拆分为元组列表

Python / Regex拆分特定格式的返回字符串

如何基于以Python中特定字符结尾的分隔符字符串拆分字符串列表?

在列表和字典的字典中查找字符串

在包含特定字符串的列表列表中返回列表的索引

特定元素的列表中的正则表达式/拆分字符串

从字符串返回字典值作为元组或列表

Python字典:返回列表或字符串中的第一个值

如何返回字典列表中字符串最长的对象?(蟒蛇)

在字典列表中的列表中搜索字符串

按空格在列表列表中拆分字符串

如何用空格字符在列表中拆分字符串