The use of python-function function (II.)

Source: Internet
Author: User

Defining functions with optional parameters

Optional parameters can be assigned (by defining = ), the parameter name of the default value:

def make (action='nothing'):    return action

This function can be called in 3 different ways:

Make ('fun ')#  out:funmake(Action="  Sleep")#  out:sleep## # not Passed in. Make ()    # out:nothing
Warning

variable type ( list , dict , set and so on), should be careful when given to be considered default property. Any mutation of the default parameter will change permanently.

LAMBDA (inline/anonymous) functions

the lambda keyword to create an inline function that contains an expression.

Consider features:

def greeting ():     return " Hello "

Wherein, when called:

Print (Greeting ())

Print:

Hello

lambda S can also accept parameters:

Lambda S:s.strip (). Upper () strip_and_upper_case ("  Hello   ")

Return string:

HELLO

They can even take any number of parameters/keyword parameters, such as normal functions.

Greeting = lambda x, *args, **kwargs:print (x, args, Kwargs) greeting (' Hello ', ' world ', world= ' world ')

Print:

Hello ('World',) {'World ' }

The most common use cases lambda are short functions that are used only in one place. For example, this line arranges a list of strings, ignores their case, and ignores spaces at the beginning and end:

They are most commonly used sorted , filter andmap

Sorted (["" "    BAR""BaZ    "  "qux"], key=Lambda s:s.strip (). Upper ())

Return:

['    BAR'BaZ     ' ' Qux ']

==================================================== =========

Sorted (["" "    BAR""BaZ    "  "qux"], key=Lambda s:s.strip ())

Return:

 [ "  BAR   ' ,  '  baz   ' ,  '   foo   ' ,  '  qux   ' ] #   No effect of lambda, list is sorted 
Sorted (["" "    BAR""BaZ    "  "qux"])

Return:

 [ "  BAR   ' ,  '  baz   ' ,  '   foo   ' ,  '  qux   ' ] #   list sorted.  
Sorted (Map (Lambda s:s.strip (). Upper (), ["" "    BAR"  "BaZ    " "qux"]))

Return:

['BAR'BAZ'FOO' Qux ' # What expected
is the first idiom wrong? Can you explain this, please?

==================================================== =====================

My_list = [3, -4,-2, 5, 1, 7]sorted (my_list, key=Lambda x:abs (x))

Return:

[1,-2, 3,-4, 5, 7]
List (filter (lambda x:x>0, my_list)

Return:

[3, 5, 1, 7]
List (map (lambda x:abs (x), my_list)

Return:

[3, 4, 2, 5, 1, 7]

Other functions (with/without parameters) can be called from within a lambda function.

def foo (msg):     Print  Lambda"helloWorld": foo (x) greet ()

Print:

Hello World

Because this is very useful lambda can only contain one expression and can run multiple statements by using one of the subordinate functions.

Attention

Remember, PEP-8 ( The official Python style guide) does not recommend that a lambda expression be assigned to a variable (as in the first two examples):

Always use the DEF statement instead of binding the lambda expression directly to the assignment statement of the identifier.

Is:

def return 2*x

No:

Lambda x:2*x

The first form refers to the resulting function where the name of the object is special f , rather than the generic <lambda> . This is more useful for general tracking and string representations. The only good thing to eliminate with an assignment statement is that a lambda expression can provide an explicit def declaration (that is, it can be embedded in a larger expression).

The use of python-function function (II.)

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.