【问题标题】:Update item in dict comprehension python [duplicate]更新dict理解python中的项目[重复]
【发布时间】:2020-07-30 17:51:44
【问题描述】:
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)
# Expected Output
# {'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}

在这里,我想使用 dict/list 理解获得相同的输出。 期待简单而简短的代码。

【问题讨论】:

    标签: python list-comprehension dictionary-comprehension


    【解决方案1】:

    一个简短的单行代码:

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

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

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

    【讨论】:

      【解决方案2】:

      你可以使用collections.Counter:

      from collections import Counter
      
      words_count = Counter(words)
      

      【讨论】:

        【解决方案3】:

        您可以在不使用任何导入的情况下计算这一点,并使用尽可能少的.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 将产生唯一值。

        【讨论】:

        • 这很慢!!它以二次时间运行!这就是我投反对票的原因
        • 是的,我喜欢它......即使这可能在计数器模块内执行相同的操作。
        猜你喜欢
        • 2022-11-13
        • 2020-03-01
        • 1970-01-01
        • 2015-06-23
        • 2020-07-19
        • 2021-10-17
        • 2019-06-27
        • 2021-06-18
        相关资源
        最近更新 更多