Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of sets

Tags:

python

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?

like image 314
hymloth Avatar asked Aug 30 '11 12:08

hymloth


2 Answers

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!

like image 152
Adam Matan Avatar answered Nov 13 '22 17:11

Adam Matan


if L is the list of sets

sorted(L, key=len, reverse=True)

or to sort in place

L.sort(key=len, reverse=True)
like image 42
John La Rooy Avatar answered Nov 13 '22 17:11

John La Rooy