What is the right Python idiom for sorting by a single criterion (field or key)? [closed]

2024/10/5 20:23:45

As in title, how can I sort objects by single criterion?

I've heard about key parameter, cmp parameter, and Decorate-Sort-Undecorate pattern.
Which one should I use in modern Python, and how?

Answer

In modern Python, the best way is to use list.sort or sorted with key argument.

When you pass key argument, sorting function, instead of comparing elements directly, compares whatever key returned for them.

So, you can pass as key any callable that takes element to be sorted as single positional argument, and returns what the element should be sorted by.
The callable will be called once for each element.

Some simple examples:

   list_ = ['B', 'aaa', 'CC']sorted(list_)
=> ['B', 'CC', 'aaa']# case-insensitive sortingsorted(list_, key=str.lower)
=> ['aaa', 'B', 'CC']# sorting by lengthsorted(list_, key=len)
=> ['B', 'CC', 'aaa']

Sorting with key is roughly equivalent to Decorate-Sort-Undecorate pattern:

def decorate_sort_undecorate(iterable, key):# 1: decorate:decorated = [(key(elem), index, elem) for index, elem in enumerate(iterable)]# 2: sort:decorated.sort()# 3: undecorate: return [elem for key_, index, elem in decorated]

This creates temporary list (decorated) of 3-element tuples,
which have form: (key_, index, elem), where key_ = key(elem). Then, decorated list is sorted.
Tuples are compared by first non-equal element. This is key_, or if key_s are equal, index. Because there are no equal indexes, elements are never directly compared.
At the end, elements are extracted from decorated into new list, which is returned.

Random thoughts:

  • Order of sorted elements can be reversed using reverse=True,
  • lambdas and functions from operator module are often passed as key,
  • before 2.4, there were no key parameter. There were only Decorate-Sort-Undecorate pattern and slow cmp parameter,
  • Sorting a Python list by two criteria.
https://en.xdnf.cn/q/119026.html

Related Q&A

Incorrect checking of fields in list using a for loop

I have the following code that seeks to read the file contents into a list (this bit works) and then display a message of acceptance, IF the bank details (user and corresponding number) matches. e.g. i…

Why myVar = strings.Fields(scanner.Text()) take much more time than comparable operation in python?

Consider the following code in golangnow := time.Now() sec1 := now.Unix()file, err := os.Open(file_name) if err != nil {log.Fatal(err) } defer file.Close()scanner := bufio.NewScanner(file)var parsedLin…

When reading an excel file in Python can we know which column/field is filtered

I want to capture the field or column name that is filtered in the excel file when reading through python. I saw that we can also capture only the filtered rows by using openpyxl and using hidden == Fa…

Error:__init__() missing 1 required positional argument: rec

I am new to python. I am trying to do microphone file that ought to detect, listen, record and write the .wav files. However, it is giving me an error while I am trying to run the file. It is saying:Ty…

Maya: Connect two Joint chains with Parent Constraint

So here is a snipit of an IK spine builder Ive been working on. Ive figure out how to make lists to duplicate the bound into an IK chain, what Ive got stuck on however is I want my list and for loop to…

What is the equivalent for onkeydown and onkeyup (Javascript events) in python?

There are events called onkeydown and onkeyup in Javascript. Can anyone please suggest the python equivalent of it?

Matching number string pairs

I have the following sample string:R10666: 273141 C1 + 273141 C2 + 273141 C3 + 273141 C4 + 273141 C5 - 273141 C6I want to obtain:[(273141,C1), ..., (- 273141, C6)]The numbers can be floating point numb…

Turning a text file into a tabular format [duplicate]

This question already has answers here:How do I print parameters of multiple objects in table form? [duplicate](2 answers)Line up columns of numbers (print output in table format)(7 answers)Closed 5 y…

Python: Read file with list as list

I have placed a list in a text file. I want python to read the text file and return the contents as a list. However, it is instead reading the content as a string:Text file:[a,b,c]Python:ids=[]writtenF…

Tkinter scrollbar not scrollable

I followed some tutorial on attaching a scrollbar to a textbox. However, in the tutorial, the scrollbar is really a "bar". When I tried myself, I can only press the arrows to move up or down,…