dict理解python中的更新项目

问题描述 投票:1回答:3
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}

这里我想使用字典/列表理解获得相同的输出。期望简单而简短的代码。

python list-comprehension dictionary-comprehension
3个回答
3
投票

您可以使用:

from collections import Counter

words_count = Counter(words)

1
投票

一个简短的单行代码:

{i:words.count(i) for i in words}

这里,我们根据单词的数量创建字典。给出:

{'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}

0
投票

您可以数不使用任何导入并且通过以下方式使用尽可能少的.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将得到唯一的值。

© www.soinside.com 2019 - 2024. All rights reserved.