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

查看:28
本文介绍了如何通过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 检查,但这很难看.有没有pythonic的方法?顺便说一下,对象的属性都是字符串.

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天全站免登陆