Custom comparison functions in python3.x _python

Source: Internet
Author: User
Tags anonymous

In the python3.x world, CMP functions are gone. So what about Sorted,min,max functions that need to compare functions as arguments?

Take the definition of the Min function as an example, there are two overloaded forms:

Single parameter (an iterator):

Copy Code code as follows:

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

Multiple parameters (multiple items to compare):

Copy Code code as follows:

Min (A, B, C, ...) [, Key=func]) -> value

This paper mainly discusses the use of key=func parameters. For example, let's say:

1. Comparison of custom objects
I defined a class test with two member variables A and B:

Copy Code code as follows:

Class Test:
def __init__ (self,a,b):
SELF.A = A
SELF.B = b

The three objects were then instantiated x,y,z:
Copy Code code as follows:

X=test (a ' x ')
Y=test (2, ' Y ')
Z=test (8, ' Z ')

I want them to compare the variable A to the smallest object of a:
Copy Code code as follows:

Mintest=min (X,y,z,key=lambda t:t.a)

Because the key parameter needs to pass in a function, it is convenient to use the Lambda anonymous function. In this example, to implement the comparison function (or, to be exact, the comparison key function), so Lamda's argument as long as one, whatever you name (I use T), on behalf of the object to be compared (ie a,b,c); the colon is followed by the expression, which directly returns the member variable a of T.

Thus, the Min function (which is similar to a max,sorted function) will be compared according to the value of a for each object to be compared, returning the object with the smallest value of a (reference) to Mintest.

The output is mintest.a,mintest.b to verify the results.

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

Copy Code code as follows:

dic={' B ': 3, ' a ': 5, ' C ': 9, ' d ': 2}

If you want to sort by the key keys of the dictionary, as long as:
Copy Code code as follows:

Sorted (DIC)

Returns a list that is a sorted key, but the value is not placed in the list:
Copy Code code as follows:

[' A ', ' B ', ' C ', ' d ']

Just use the following methods:
Copy Code code as follows:

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

What if you want to sort by value? So just pass in the parameter of the comparison function:

Copy Code code as follows:

Sorted (Dic.items (), Key=lambda d:d[1])

I continue to use the Lambda anonymous function. where d represents each iteration element in the Dic.items (), a tuple (for example (' a ', 5), an expression d[1] is the second element in the tuple (for example, 5), and it is also the value of the dictionary, which we need to compare to. Run Result:
Copy Code code as follows:

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

P.S.
Blogger today, the Python challenge encountered a pass, you need to count the number of characters appearing in the text and find the least occurrence of the characters. Of course, it does not need to write their own comparison function, output statistics to see the naked eye. Bloggers with the help of the search engine min function key=func parameters, deep pain Chinese Python introduction articles are the Old World python2.x, full of in the new world can not use the grammar, to python3.x beginners to bring a lot of misleading, harmful. So this article.

The blogger is also a Python beginner, and it is a great honor to be criticized by Daniel.

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.