Python custom class array sorting implementation code, python Array

Source: Internet
Author: User

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.

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.