2012-12-21 30 views
1

的列表字典中的值對於這樣一個列表中的Python化的方式:什麼是算在字典

for i in range(100): 
    things.append({'count':1}) 

for i in range(100): 
    things.append({'count':2}) 

要統計列表的1數量:

len([i['count'] for i in things if i['count'] == 1]) 

什麼是更好的方法?

+0

的例子是有點一般,但爲什麼不使用things.count(1)? – abought

回答

3

collections.Counter

>>> from collections import Counter 
>>> c = Counter([thing['count'] for thing in things]) 
>>> c[1]    # Number of elements with count==1 
100 
>>> c[2]    # Number of elements with count==2 
100 
>>> c.most_common() # Most common elements 
[(1, 100), (2, 100)] 
>>> sum(c.values()) # Number of elements 
200 
>>> list(c)   # List of unique counts 
[1, 2] 
>>> dict(c)   # Converted to a dict 
{1: 100, 2: 100} 

也許你可以做這樣的事情?

class DictCounter(object): 
    def __init__(self, list_of_ds): 
     for k,v in list_of_ds[0].items(): 
      self.__dict__[k] = collections.Counter([d[k] for d in list_of_ds]) 

>>> new_things = [{'test': 1, 'count': 1} for i in range(10)] 
>>> for i in new_things[0:5]: i['count']=2 

>>> d = DictCounter(new_things) 
>>> d.count 
Counter({1: 5, 2: 5}) 
>>> d.test 
Counter({1: 10}) 

擴展DictCounter處理丟失的鑰匙:

>>> class DictCounter(object): 
    def __init__(self, list_of_ds): 
     keys = set(itertools.chain(*(i.keys() for i in list_of_ds))) 
     for k in keys: 
      self.__dict__[k] = collections.Counter([d.get(k) for d in list_of_ds]) 

>>> a = [{'test': 5, 'count': 4}, {'test': 3, 'other': 5}, {'test':3}, {'test':5}] 
>>> d = DictCounter(a) 
>>> d.test 
Counter({3: 2, 5: 2}) 
>>> d.count 
Counter({None: 3, 4: 1}) 
>>> d.other 
Counter({None: 3, 5: 1})