Functiontools module, pythonfunctiontools

Source: Internet
Author: User

Functiontools module, pythonfunctiontools

#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
From functools import cmp_to_key

A = [1, 6, 4, 5]
A. sort (key = cmp_to_key (lambda x, y: x-y ))
# Cmp_to_key (lambda x, y: x-y) is a k class
# When x = 4, y = 3, Class k is instantiated. mycamp is lambda x, y: x-y return x-y.
# First, when performing sort comparison, the elements in the list are instantiated and passed in.
# Self. obj = 4 other. obj = 3
# By default, the sort function is arranged from small to large. During the comparison process, the _ gt _ function is automatically triggered because it is larger than 4,
# The Return Value of mycmp is 4-3 = 1, and then compare it with 0. 1> 0. Therefore, the return value of cmp_to_key (mycmp) is True.
# So forward order
# If mycamp is lambda x, y: x-y return y-x
# Self. obj = 4 other. obj = 3
# By default, the sort function is arranged from small to large. During the comparison process, the _ gt _ function is automatically triggered because it is larger than 4,
# The Return Value of mycmp is 3-4 =-1, and then compare it with 0.-1 <0, so the return value of cmp_to_key (mycmp) is False.
# So sort in reverse order
Def cmp_to_key (mycmp ):
"Convert a cmp = function into a key = function """
Class K (object ):
_ Slots _ = ['obj ']
Def _ init _ (self, obj, * args ):
Self. obj = obj
Def _ gt _ (self, other ):
Return mycmp (self. obj, other. obj)> 0
Def _ gt _ (self, y): # real signature unknown; restored from _ doc __
"" X. _ gt _ (y) <=> x> y """
Pass
Return K

Related Article

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.