按对象特征创建列表的字典 [英] Create dictionary of lists by object feature

查看:125
本文介绍了按对象特征创建列表的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个类:

class Cat(object):
     color = "White"     # "Black", "Red" or whatever
     name = "..."
     ....

如果我有猫的名单,我想通过颜色将它们分开,放在列表的字典:

If I have a list of cats, I want to separate them by color and put in dictionary of lists:

cats = [cat1, cat2, cat3, ...]
cats_by_color = {"White": [cat1, cat3, ...], "Black": [...], ...}

现在我这样做:

cats_by_color ={}
for cat in cats:
    if cat.color not in cats_by_color.keys():    # add new key if needed
        cats_by_color[cat.color] = []
    cats_by_colors[cat.color].append(cat)        # add cat to right list

和我有一个强烈的感觉,有做这样的事情更pythonish方式。如何通过一些单行办呢?

And I have a strong feeling that there is a "more pythonish way" of doing such things. How to do it by some one-liner?

推荐答案

要做到在一个班轮,你需要首先对列表进行排序,然后使用的 itertools.groupby()

To do it in a one-liner, you'd need to sort the list first, then use itertools.groupby():

from operator import attrgetter
from itertools import groupby

color = attrgetter('color')
cats_by_color = {k: list(g) for k, g in groupby(sorted(cats, key=color), color)}

不过,排序不仅仅是直循环更昂贵;这不再是一个班轮,但使用 collections.defaultdict() 至少使得紧凑:

However, sorting is more costly than just a straight loop; this is no longer a one-liner, but using collections.defaultdict() at least makes it compact:

from collections import defaultdict

cats_by_color = defaultdict(list)

for cat in cats:
    cats_by_colors[cat.color].append(cat)

下面 defaultdict 将创建一个新的列表对象键是没有在字典中,仅仅通过努力访问密钥。

Here defaultdict will create a new list object for keys that are not yet in the dictionary, merely by trying to access the key.

这篇关于按对象特征创建列表的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆