words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {}
for word in words:
words_count[word] = words_count.get(word,0)+1
print(words_count)
//output
//{'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}
这里我想使用字典/列表理解获得相同的输出。期望简单而简短的代码。
您可以使用:
from collections import Counter
words_count = Counter(words)
一个简短的单行代码:
{i:words.count(i) for i in words}
这里,我们根据单词的数量创建字典。给出:
{'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}
您可以数不使用任何导入并且通过以下方式使用尽可能少的.counts
:
words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {i:words.count(i) for i in set(words)}
print(words_count) # {'surendra': 2, 'mahesh': 6, 'rocky': 2, 'deepak': 1}
将list
转换为set
将得到唯一的值。