Python custom class array sort implementation code

  • 2020-05-10 18:25:05
  • OfStack

First of all, write out the implementation method, it is actually very simple, only need 1 sentence of code can:


productlist.sort(lambda p1, p2:cmp(p1.getPrice(), p2.getPrice()))

The array productlist stores the custom class Product. One method of Product is to return the price of the goods. Thus, productlist is sorted from low to high according to the price of Product.

Python is really a simple and powerful language. In fact, I didn't really feel the charm of this language until I wrote 1 line of code.

By the way, I'd like to introduce you to lambda expressions. Many languages now support lambda expressions, including.Net.

The lambda function 1 is also known as an anonymous function. Let's take a look at one of the simplest examples:


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 you can see from the above example, the lambda statement actually builds a function object. The biggest feature of lambda is that it can eliminate the process of defining functions and make the code more concise.

About the syntax of lambda
In the lambda statement, the colon is preceded by a parameter, which can be multiple, separated by a comma. To the right of the colon is the return value.


Related articles: