加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

是否在Python中优化了重复的字典访问

发布时间:2020-12-20 11:03:25 所属栏目:Python 来源:网络整理
导读:考虑以下 Python代码,迭代一个单词数组并将它们计入字典a [‘words’] a['words'] = {}for word in words: if word not in a['words']: a['words'][word] = 0 a['words'][word] += 1 问题是,是否在Python中优化了对[‘words’]的重复访问,使得[‘words’]的
考虑以下 Python代码,迭代一个单词数组并将它们计入字典a [‘words’]

a['words'] = {}
for word in words:
    if word not in a['words']:
        a['words'][word] = 0
    a['words'][word] += 1

问题是,是否在Python中优化了对[‘words’]的重复访问,使得[‘words’]的引用自动保存到某处直到更改,或者我应该自己编写“优化”代码,这条路:

a['words'] = {}
words_dict = a['words']
for word in words:
    if word not in words_dict:
        words_dict[word] = 0
    words_dict[word] += 1

解决方法

好的解决方案是 collections.Counter,因为它是高性能容器:

from collections import Counter
words = ['aaa','bbb','ccc','ddd','aaa','eee']
a = {'words' : dict(Counter(words))}
a
#{'words': {'aaa': 2,'bbb': 2,'ccc': 1,'ddd': 1,'eee': 1}}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读