I have a list of sets on which I want to perform intersection.
Is there an efficient way to sort those sets by length, in order to optimize calculations?
The key
argument of sort
allows custom sort keys. Using len
will do the trick:
l=<list_of_sets>
l.sort(key=len)
If you want the longest set first, use the reverse
argument:
l.sort(key=len, reverse=True)
For example:
>>> l=[set((1,2,5,6,7)), set((1,2,3,4,5,6,7)), set((1,)), set((1,2,3))]
>>> l
[set([1, 2, 5, 6, 7]), set([1, 2, 3, 4, 5, 6, 7]), set([1]), set([1, 2, 3])]
>>> l.sort(key=len)
>>> l
[set([1]), set([1, 2, 3]), set([1, 2, 5, 6, 7]), set([1, 2, 3, 4, 5, 6, 7])]
>>> l.sort(key=len, reverse=True)
>>> l
[set([1, 2, 3, 4, 5, 6, 7]), set([1, 2, 5, 6, 7]), set([1, 2, 3]), set([1])]
Update: Learned something today - lambda isn't necessary, because len
is used without extra arguments. Therefore, l.sort(lambda x:len(x))
is equivalent to l.sort(key=len)
. Thanks, Eugene Homyakov!
if L is the list of sets
sorted(L, key=len, reverse=True)
or to sort in place
L.sort(key=len, reverse=True)
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