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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With