如何在python中按相似的索引/属性对元组/对象列表进行分组? [英] How to group a list of tuples/objects by similar index/attribute in python?

查看:97
本文介绍了如何在python中按相似的索引/属性对元组/对象列表进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供列表

old_list = [obj_1, obj_2, obj_3, ...]

我要创建一个列表:

new_list = [[obj_1, obj_2], [obj_3], ...]

其中obj_1.some_attr == obj_2.some_attr.

我可以把一些for循环和if检查放在一起,但这很丑陋.有没有Python的方式呢?顺便说一下,对象的属性都是字符串.

I could throw some for loops and if checks together, but this is ugly. Is there a pythonic way for this? by the way, the attributes of the objects are all strings.

或者,对于包含元组(具有相同长度)而不是对象的列表的解决方案也很受欢迎.

推荐答案

defaultdict 是如何做到的.

defaultdict is how this is done.

虽然for循环在很大程度上是必需的,但if语句不是必需的.

While for loops are largely essential, if statements aren't.

from collections import defaultdict


groups = defaultdict(list)

for obj in old_list:
    groups[obj.some_attr].append(obj)

new_list = groups.values()

这篇关于如何在python中按相似的索引/属性对元组/对象列表进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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