【问题标题】:Python list comprehension for dictionaries an example字典的 Python 列表理解示例
【发布时间】:2014-02-24 23:30:29
【问题描述】:
I have the following script:

dict_class = dict()
for p in points:
    dict_class[p.class] = dict_class.get(p.class, 0) + 1

print dict_class
{1: 1314, 2: 1050}

其中“points”是一个值列表。 我的问题是,是否可以转换字典的列表理解以加快我的代码速度?

【问题讨论】:

  • @Bill:还没有这个循环,因为那需要自我引用。

标签: python performance optimization dictionary list-comprehension


【解决方案1】:
from collections import Counter 
from operator import attrgetter
Counter(map(attrgetter("class"),points))

【讨论】:

    猜你喜欢
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2018-03-18
    • 2021-03-12
    相关资源
    最近更新 更多