Let's say I have a list like this:
list = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
How can I most elegantly group this to get this list output in Python:
list = [["A", "C"], ["B"], ["D", "E"]]
So the values are grouped by the secound value but the order is preserved...
I don't know about elegant, but it's certainly doable:
This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.
.
EDIT
Another solution that needs no import , is more readable, keeps the orders, and is 22 % less long than the preceding one:
Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use
itertools.groupby
:Edit:
I changed this after seeing eyequem's answer:
itemgetter(1)
is nicer thanlambda x: x[1]
.You can do it in a single list comprehension, perhaps more elegant but O(n**2):