How to sort a list of list based on the same set value in the list?

Viewed 108
a = [['a', 'b'], ['b'], ['b', 'a']]

Because the 1st and 3rd element are the same, if they are converted to a set, I want to sort the list 'a' so that any two elements with the same set value would be next to each other. For the example above, the sorted result would be:

a = [['a', 'b'], ['b', 'a'], ['b']]

OR

a = [['b'], ['a', 'b'], ['b', 'a']]
2 Answers

You could use list(set(x)) as your key. Since the ordering this imposes would be a bit arbitrary, you could add sorted to the mix:

a = [['a', 'b'], ['b'], ['b', 'a']]
a.sort(key=lambda x: sorted(set(x)))

Note that this is not the same as using key=sorted because of how duplicate elements are handled.

One way using hash with frozenset:

sorted(a, key=lambda x: hash(frozenset(x)))

Output:

[['b'], ['a', 'b'], ['b', 'a']]

Tested with more elemenets:

a = [['a', 'b', 'c'], ['a', 'b'], 
     ['b'], ['b', 'd'], ['b', 'a'], 
     ['a', 'c'], ['b', 'c', 'a']]
sorted(a, key=lambda x: hash(frozenset(x)))

Output:

[['a', 'c'],
 ['a', 'b', 'c'],
 ['b', 'c', 'a'],
 ['b'],
 ['b', 'd'],
 ['a', 'b'],
 ['b', 'a']]
Related