這是我正在上課的一個練習。我將此發佈到留言板,得到的反饋表明我只使用姓名列表中的姓氏。最終,當它運行時,它只返回 {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))
問題是兩個 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] 删除。
我来说两句