Python custom class array sort implementation code _python

Source: Internet
Author: User

First, the implementation of the method written out, in fact very simple, only need a code can:

Copy Code code as follows:

Productlist.sort (Lambda P1, p2:cmp (P1.getprice (), P2.getprice ()))

The product,product of a custom class is stored in the array productlist a method is to return the price of the commodity, and then the productlist is sorted from lowest to highest price, which requires just such a simple line of code.

Python really is a simple and powerful language, in fact, I also from writing a line of code, I really feel the charm of the language.

Here, by the way, for the knowledge of lambda expressions, many languages now support lambda expressions, even. Net.

A lambda function is also called an anonymous function, first of all, to see the simplest example:

def test (x): Return
 x**2
print test (4)

If you use a lambda, the syntax is as follows:

Test = lambda x:x**2
print test (4)

As you can see from the example above, a lambda statement is actually a function object, and the biggest feature of the lambda is that it eliminates the process of defining the function and makes the code more streamlined.

About the syntax of a lambda
In a lambda statement, the colon is preceded by a parameter, can be multiple, separated by commas, and 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.