Skip to main content

Sort a sequence, preferring some values

Project description Documentation Status Updates

Partially sort a sequence, preferring some values.

from prefsort import prefsorted

seq = list('abcde')

seq2 = prefsorted(seq, 'c b')
assert seq2 == ['c', 'b', 'a', 'd', 'e']

Note that this doesn’t sort the majority of the sequence in the way Python’s normal list.sort() or sorted() do. It just pulls the preferred members to the front of the list.

This is particularly handy to have when organizing data columns, for example with pandas, the following will make sure the id and name columns come first in a DataFrame:

df = df.reindex(columns=prefsorted(df.columns, 'id name'))

There is also a reverse parameter that will put the “preferred” items at the end of the list. In this case it’s a “negative preference.”

seq2 = prefsorted(seq, 'c b', reverse=True)
assert seq2 == ['a', 'd', 'e', 'c', 'b']

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for prefsort, version 0.1.0
Filename, size File type Python version Upload date Hashes
Filename, size prefsort-0.1.0-py2.py3-none-any.whl (3.4 kB) File type Wheel Python version py2.py3 Upload date Hashes View
Filename, size prefsort-0.1.0.tar.gz (3.5 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page