Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a set of values

Tags:

python

People also ask

How do you sort values in a set?

Sorted() Method This is a pre-defined method in python which sorts any kind of object. In this method, we pass 3 parameters, out of which 2 (key and reverse) are optional and the first parameter i.e. iterable can be any iterable object This method returns a sorted list but does not change the original data structure.

Can you order a set in Python?

Python allows you to create ordered sets in your programs. Below we'll demonstrate two ways to do so: using Python's ordered-set package, and a manual method.

How do you sort a set in alphabetical order?

Select the list you want to sort. Go to Home > Sort. Set Sort by to Paragraphs and Text. Choose Ascending (A to Z) or Descending (Z to A).


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.