# Python代码阅读（第7篇）：列表分组计数

## `count_by`

``````def count_by(arr, fn=lambda x: x):
key = {}
for el in map(fn, arr):
key[el] = 1 if el not in key else key[el] + 1
return key

# EXAMPLES
from math import floor
count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}``````

`count_by`根据给定的函数对列表中的元素进行分组，并返回每组中元素的数量。该使用map()使用给定函数映射给定列表的值。在映射上迭代，并在每次出现时增加元素数。

## 使用字典推导式

``````def count_by(lst, fn):
return {key : len([el for el in lst if fn(el) == key]) for key in map(fn, lst)}``````

## 使用`collections.defaultdict`简化代码

``class collections.defaultdict([default_factory[, ...]])``

`collections.defaultdict`包含一个`default_factory`属性，可以用来快速构造指定样式的字典。

`````` from collections import defaultdict

def count_by(lst, fn):
d = defaultdict(int)
for el in lst:
d[fn(el)] += 1
return d``````

``````def group_by(lst, fn):
d = defaultdict(list)
for el in lst:
d[fn(el)].append(el)
return d

# EXAMPLES
from math import floor
group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}``````