Python 3 sorted and comparison functions

In Python 3, you can no longer pass a comparison function to the sorted function, but in Python 3.2 you can use functools.cmp_to_key to do the same thing as passing a comparison function to the sorted function. Let's write some samples.

First, let's write a sample that compares and sorts integers by strings.

python


from functools import cmp_to_key

def cmp(a, b):
    if a == b: return 0
    return -1 if a < b else 1
    
def cmpstr(a, b):
    return cmp(str(a), str(b))

def main():
    xs = [4, 90, -9, 12, 42]
    print(sorted(xs, key=cmp_to_key(cmpstr)))

main()

This is the execution result.

[-9, 12, 4, 42, 90]

The magnitude comparison result returns -1, 0, or 1. Returns -1 if less, 0 if equal, 1 if greater.

However, in this example only, writing sorted (xs, key = str) is the same.

Now that I know how to use functools.cmp_to_key, I'll try the sort I really wanted to do. I have a list of tuples with two elements and I want to sort this list. The comparison method sorts the tuples in ascending order of the second element, and if the second element is equal, in descending order of the first element. The comparison function looks like this:

python


from functools import cmp_to_key

def cmp(a, b):
    if a == b: return 0
    return -1 if a < b else 1

def cmptuple(a, b):
    return cmp(a[1], b[1]) or cmp(b[0], a[0])

def main():
    xs = [(4, 90), (-9, 12), (42, 12), (100, 12), (1, 1), (-123, 1)]
    print(sorted(xs, key=cmp_to_key(cmptuple)))

main()

This is the execution result.

[(1, 1), (-123, 1), (100, 12), (42, 12), (-9, 12), (4, 90)]

Link

Recommended Posts

Python 3 sorted and comparison functions
About python dict and sorted functions
Python higher-order functions and comprehensions
Python functions
Java and Python basic grammar comparison
[Python] Difference between sorted and sorted (Colaboratory)
Comparison of how to use higher-order functions in Python 2 and 3
First Python 3 ~ First comparison ~
Precautions when passing def to sorted and groupby functions in Python? ??
#Python basics (functions)
[Beginner] Python functions
Python Easy-to-use functions
Python basics: functions
Use Python and MeCab with Azure Functions
Correspondence between Python built-in functions and Rust
Julia Quick Note [22] Calling Python functions and Python modules
Comparison of R and Python writing (Euclidean algorithm)
A story about modifying Python and adding functions
cv2 functions and data types (OpenCV python bindings)
Comparison of Python and Ruby (Environment / Grammar / Literal)
Python> Sort by number and sort by alphabet> Use sorted ()
Sorted list in Python
[python] Compress and decompress
Python Beginner's Guide (Functions)
Python and numpy tips
Python SDP runtime comparison
[Python] pip and wheel
Batch design and python
Higher-order functions and decorators
Python iterators and generators
Python packages and modules
Vue-Cli and Python integration
[Python] Memo about functions
python input and output
Python and Ruby split
# 4 [python] Basics of functions
Python built-in functions ~ Zip ~
Python package manager comparison
Wrap Python built-in functions
Python3, venv and Ansible
Python asyncio and ContextVar
Anonymous and map functions
[Introduction to Udemy Python3 + Application] 35. Comparison operators and logical operators
[Python for Hikari-] Chapter 06-04 Functions (arguments and return value 3)
File write speed comparison experiment between python 2.7.9 and pypy 2.5.0
[Ruby vs Python] Benchmark comparison between Rails and Flask
A quick comparison of Python and node.js test libraries
[Ubuntu] [Python] Face detection comparison between dlib and OpenCV
[Python for Hikari-] Chapter 06-01 Functions (Intrinsic Functions and Function Definitions)
Comparison table of frequently used processes of Python and Clojure
Paiza Python Primer 2: Learn Conditional Branching and Comparison Operators
[Python for Hikari-] Chapter 06-03 Functions (arguments and return value 2)
[Python] Chapter 05-01 Control syntax (comparison operator and conditional branching)
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
Curry arbitrary functions with Python ....
Programming with Python and Tkinter
Python> lambda> tiny functions / callback functions
Getting Started with Python Functions
Python: Class and instance variables
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-