140
votes

I have values like this:

set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
set(['4.918859000', '0.060758000', '4.917336999', '0.003949999', '0.013945000', '10.281522000', '0.025082999'])  

I want to sort the values in each set in increasing order. I don't want to sort between the sets, but the values in each set.

1
What do the tuples have to do with the problem and what have you tried? - Fred Foo
I don't think python sets have a concept of ordering. This might help you: stackoverflow.com/questions/1653970/… - zallarak
a set is orderless. that's one of it's properties. in every language. use a list. - Karoly Horvath
@JustinCarrey: Since the stuff about the dictionary is irrelevant, and referring to a set of values as a list of values is confusing, I've stripped all of that out of the question. If you don't think the edited version reflects your actual problem, please revert it (or, if you don't have enough rep, just ask me to do it for you). - abarnert
@KarolyHorvath "a set is orderless. that's one of it's properties. in every language." C++'s std::set is ordered. - Timothy Shields

1 Answers

263
votes

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.