Python custom class array sorting implementation code, python Array
First, write the implementation method, which is actually very simple. You only need a code sentence:
Copy codeThe Code is as follows:
Productlist. sort (lambda p1, p2: cmp (p1.getPrice (), p2.getPrice ()))
The custom Product class is stored in the array productlist. One method of Product is to return the Product price, so the productlist is sorted from low to high according to the Product price, you only need such a simple line of code.
Python is really a simple and powerful language. In fact, I actually feel the charm of this language only after writing a line of code.
Here, I will introduce the knowledge of lambda expressions. Many languages now support lambda expressions, and even include. Net.
Lambda functions are also called anonymous functions. Let's take a look at the simplest example:
Def test (x): return x ** 2 print test (4)
If lambda is used, the syntax is as follows:
Test = lambda x: x ** 2 print test (4)
As shown in the preceding example, a lambda statement is actually a function object. The biggest feature of lambda is that it can save the process of defining a function and make the code more streamlined.
Lambda syntax
In a lambda statement, there are multiple parameters before the colon, which can be separated by commas. the right side of the colon is the return value.