Python3.x custom comparison function

Source: Internet
Author: User
This article mainly introduces the custom comparison functions in Python3.x. This article provides the comparison and implementation methods of custom objects and dictionary value values. For more information, see Python3.x, the cmp function is missing. So how do I use sorted, min, max, and other functions that need to compare functions as parameters?

Taking the definition of min function as an example, there are two overload forms:

Single parameter (one iterator ):

The code is as follows:


Min (iterable [, key = func])-> value


Multiple parameters (multiple content to be compared ):

The code is as follows:


Min (a, B, c,... [, key = func])-> value


This article mainly discusses the use of the key = func parameter. For example:

1. Comparison of custom objects
I have defined a class test, which has two member variables a and B:

The code is as follows:


Class test:
Def _ init _ (self, a, B ):
Self. a =
Self. B = B


Three objects x, y, and z are instantiated:

The code is as follows:


X = test (10, 'x ')
Y = test (2, 'y ')
Z = test (8, 'z ')


I want them to compare with variable a to obtain the smallest object of variable:

The code is as follows:


MinTest = min (x, y, z, key = lambda t: t.)


Since the key parameter needs to be passed in a function, it is very convenient to use the lambda anonymous function. In this example, we need to implement a comparison function (more accurately, a comparison keyword function). Therefore, we only need one parameter for lambda. whatever name you choose (I use t ), indicates the object to be compared (that is, a, B, c). The colon is followed by an expression. here, the member variable a of t is directly returned.

Then, the min function (with max, sorted, and other functions) will compare the values of a for each object to be compared, and return the object with the smallest value of a (reference) assign a value to minTest.

Output minTest. a and minTest. B to verify the result.

2. Comparison of dictionary value values
There is a dictionary:

The code is as follows:


Dic = {'B': 3, 'A': 5, 'C': 9, 'D': 2}


If you want to sort keys based on the dictionary, as long:

The code is as follows:


Sorted (dic)


A list is returned, which is the sorted key, but the value is not put into the list:

The code is as follows:


['A', 'B', 'C', 'D']


Use the following methods:

The code is as follows:


>>> Sorted (dic. items ())
[('A', 5), ('B', 3), ('C', 9), ('D', 2)]


What if we want to sort values by value? Then we can pass in the parameter of the comparison function:

The code is as follows:


Sorted (dic. items (), key = lambda d: d [1])


I continue to use lambda anonymous functions. D indicates dic. each iteration element in items (), that is, a tuples (for example ('A', 5); expression d [1] is the second element in the tuples (for example, 5 ), it is also the value of the dictionary, and we need to take it as a comparison standard. Running result:

The code is as follows:


[('D', 2), ('B', 3), ('A', 5), ('C', 9)]


P.S.
Today, The Python Challenge encountered a critical issue. you need to count The number of characters in The text and find The minimum number of characters. Of course, you don't need to write a comparison function on your own. The output result is visible to the public. With the help of the key = func parameter of the search engine min function, the introduction of Python in deep pain Chinese is the world of Python2.x, and is full of the syntax unavailable in the New World, it is misleading and harmful to beginners of Python3.x. Therefore, this article is published.

The blogger is also a beginner in Python. it is a great honor to criticize and correct him.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.