Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group a list of tuples/objects by similar index/attribute in python?

Given a list

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

I want to create a list:

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

where obj_1.some_attr == obj_2.some_attr.

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.

Alternatively a solution for a list containing tuples (of the same length) instead of objects is appreciated, too.

like image 445
Aufwind Avatar asked Jul 06 '11 19:07

Aufwind


People also ask

How can you say that a tuple is an ordered list of objects?

Answer: because tuples don't contain lists, strings or numbers. They contain references to other objects. The inability to change the sequence of references a tuple contains doesn't mean that you can't mutate the objects associated with those references.

What is difference between list and tuple in Python?

The primary difference between tuples and lists is that tuples are immutable as opposed to lists which are mutable. Therefore, it is possible to change a list but not a tuple. The contents of a tuple cannot change once they have been created in Python due to the immutability of tuples.

Is Python list ordered?

The important characteristics of Python lists are as follows: Lists are ordered. Lists can contain any arbitrary objects. List elements can be accessed by index.


1 Answers

defaultdict is how this is done.

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() 
like image 195
S.Lott Avatar answered Sep 22 '22 12:09

S.Lott