Python中有没有可以对容器进行分类的库或函数?

比如说,我有一个 list

>>> l = [2, 3, 4, 5, 2, 3, 4, 2, 6, 4, 3]

我还有一个函数

>>> fn = lambda x: x%2 

我想根据把 l 的每个元素作用到函数 fn 上
根据其返回值分类

>>> SOME_FUNCTION(fn, l)
{
    0: [2, 4, 2, 4, 2, 6, 4],
    1: [3, 5, 3, 3]
}

有这种工具吗? (虽然写一个也不麻烦)
感谢


Python中有没有可以对容器进行分类的库或函数?

6 回复

没有


Python标准库的collections模块里就有现成的分类工具。defaultdict是最常用的,它能自动为不存在的键创建默认容器(比如列表、集合),特别适合做分类统计。

给你个具体例子,假设我们有一堆单词,想按首字母分组:

from collections import defaultdict

words = ['apple', 'banana', 'apricot', 'blueberry', 'cherry', 'avocado']
grouped = defaultdict(list)  # 自动创建空列表作为默认值

for word in words:
    key = word[0]  # 按首字母分类
    grouped[key].append(word)

# 转回普通字典查看结果
print(dict(grouped))
# 输出:{'a': ['apple', 'apricot', 'avocado'], 
#       'b': ['banana', 'blueberry'], 
#       'c': ['cherry']}

如果你想要更简洁的写法,可以用itertools.groupby,但要注意它要求输入数据已经按分类键排序:

from itertools import groupby

words.sort(key=lambda x: x[0])  # 必须先排序
for key, group in groupby(words, key=lambda x: x[0]):
    print(key, list(group))

简单说,用defaultdict最省事。

d = {}
for x in l:
r = f(x)
if r in d:
d[r].append(x)
else:
d[r] = [x]
这样?


. def classify(classifier, container):
. ret = defaultdict(list)
. for i in container:
. ret[classifier(i)].append(i)
. return ret

itertools.groupby

听你的需求像是 itertools.groupby,但是 group 要求先对数据进行 sort,不然会产生多组相同 key 的结果

回到顶部