内存有效的方法来获取键控字典中唯一对象属性的计数

时间:2014-03-14 16:52:06

标签: python python-2.7 dictionary

假设我有一个像这样的对象字典:

{
  'January 2014': [
    <-- OBJECT_NAME: "Steve's Object"
        CREATED: Datetime(1,1,2014)
        CREATOR: Steve -->,
    <-- OBJECT_NAME: "Another Object"
        CREATED: Datetime(1,1,2014)
        CREATOR: Jeff -->
  ],
  'February 2014': [
    <-- OBJECT_NAME: "Steve's New Object"
        CREATED: Datetime(2,1,2014)
        CREATOR: Steve -->,
    <-- OBJECT_NAME: "foo"
        CREATED: Datetime(2,1,2014)
        CREATOR: bar -->
  ]
  ...
}

现在,我想要做的是遍历此集合的所有键和列表,并返回UNIQUE创建者的计数。目的是,我希望看到每个月加入的所有“新”创作者。目前,我这样做,但效率很低:

seen_creators = []
uniq_count = collections.Counter()
for key, value in objects_by_month.iteritems():
  for obj in value:
    if obj.CREATOR not in seen_creators:
      seen_creators.append(obj.CREATOR)
      uniq_count[key] += 1
return uniq_count

结果:Counter('January 2014': 2, 'February 2014': 1)

我不禁想到有一种更有效的方法,不需要创建一个列表,无论出于什么意图和目的,都会在事后抛弃。有吗?

0 个答案:

没有答案