返回字典中的项目数
我想修改此函数以返回字典中以每个字母开头的项目数。例如:
list= ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(list))
{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}
到目前为止,我可以返回第一个字母和单词,但不能返回不同的字母数。
def letterCounter(wrdLst):
output = {}
for word in wrdLst:
letter = word[0]
if letter in output:
output[letter].append(word)
else:
output[letter] = [word]
return output
list = ["apple", "pear", "brown", "red"]
print(letterCounter(list))
这将返回字母而不是数字:输出:
{'I': ['I'], 's': ['say'], 'w': ['what'], 'm': ['mean'], 'a': ['and']}
I want to modify this function to return the number of items in the dictionary that begin with each letter. For example:
list= ['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']
print(letterCount(list))
{'I': 4, 's': 2, 'w': 2, 'm': 2, 'a': 1}
So far I can return the first letter and words, but not the number of letters that are different.
def letterCounter(wrdLst):
output = {}
for word in wrdLst:
letter = word[0]
if letter in output:
output[letter].append(word)
else:
output[letter] = [word]
return output
list = ["apple", "pear", "brown", "red"]
print(letterCounter(list))
this would return the letters instead of number: output:
{'I': ['I'], 's': ['say'], 'w': ['what'], 'm': ['mean'], 'a': ['and']}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不要附加该单词,而是增加一个计数器。
您还可以使用标准
collections
模块。Don't append the word, increment a counter.
You can also use the standard
collections
module.如果你很喜欢使用 numpy,你可以使用它独特的功能来完成你想要做的事情。在
np.unique
调用内部,我进行了列表理解,以提取每个单词的第一个字母并确保它是小写的。然后,unique 函数返回唯一的起始字母,并在启用return_counts
的情况下给出它们出现的次数。If you are cool using numpy, you can just use its unique function to do what you are trying to do. Below inside of the
np.unique
call, I do a list comprehension to pull the first letter off of each word and make sure it is lowercase. Then the unique function returns the unique starting letters and withreturn_counts
enabled gives their number of occurrences.另一个
计数器
方式:Another
Counter
way:使用违约将使代码更简洁如下:
输出:
Using a defaultdict will make the code more concise as follows:
Output:
您还可以将首字母写给字符串,然后使用str.Count()制作dict:
You can also make the initial letters to a string and then use str.count() to make the dict: