Value Set Sort

I have the following values:

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 ascending order. I do not want to sort between sets, but the values ​​in each set.

+44
python
Jul 03 '13 at 20:44
source share
1 answer

From the comment:

I want to sort each set.

It is easy. For any set s (or anything else iterative) sorted(s) returns a list of s elements 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 provides you with a list , not a set . This is because the whole point of the set, both in mathematics and in almost every programming language , * is that it is not ordered: the sets {1, 2} and {2, 1} are the same.




You probably don't really want to sort these elements as strings, but as numbers (so 4.918560000 will arrive earlier than 10.277200999, and not after).

A better solution is most likely to save the numbers as numbers, not strings. But if not, you just need to use the key function:

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



For more information, see HOWTO Sort in white papers.




* See comments for exceptions.

+99
Jul 03 '13 at 21:04 on
source share



All Articles