Jzl5325
Jzl5325

Reputation: 3974

Lexicographically sort a list of sets

In python - I have a list of sets a la

members = [set(1,2,3), set(2,4,1), set(1,3,2), set(2,1,3)]

I would like to lexicographically sort these by index, without (if possible) converting to a tuple.

If they were tuples I could simply use:

members.sort()

Since it is not possible to access a set by index without using something like iter(members[0]).next() I have not been able to use sort(key=) syntax. Perhaps I am missing something simple that will make that syntax applicable?

My goal is to avoid the set to tuple to set conversion if possible.

Edit: Given that the order of a set is not fixed I see that this is a moot point. Most of the answers below deal with a sort of the items in the set. What about a sort of the sets within the list? I ask knowing that the sort is just one potential realization as the inter-set order is not guaranteed.

Upvotes: 3

Views: 1467

Answers (3)

Oleg Razgulyaev
Oleg Razgulyaev

Reputation: 5935

members=[{1, 2, 4},{1, 2, 3}, {1, 2, 3},{1, 2, 3},{1, 2}]
members.sort(key=lambda a:",".join(map(str,sorted(a))))
members
[{1, 2}, {1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {1, 2, 4}]

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56644

>>> members = [set([1,2,3]), set([2,4,1]), set([1,3,2]), set([2,1,3])]
>>> members.sort(key=sorted)
>>> members
0: [set([1, 2, 3]), set([1, 2, 3]), set([1, 2, 3]), set([1, 2, 4])]

Upvotes: 2

6502
6502

Reputation: 114481

Your requests doesn't really make sense, lexicographical sort requires the definition of an order (sort on the first element, if the first is equivalent the compare second element and so on), but set elements are not ordered.

You can however define your custom comparison function, but it's really not clear what you're trying to do (there's no "first" element of a set).

Upvotes: 3

Related Questions