Python anonymous functions (lambda), function parameters (*args, **kwargs), Gerty, and generators

Source: Internet
Author: User
Tags generator iterable

1. anonymous function

Defined by the lambda keyword , the result of the statement is the return value, as shown below:

In [O]: def sho_function (a):
    ...: Return     a**2 ...: in [(a)

: equiv = lambda a:a**2 in [%

]: print (eq UIV (3)) #
9

2, the function of the parameters

In Python, function parameters work very simply, such as when writing function functions (A, B, C, D=some, E=value), where position and keyword parameters are packaged infinitesimal groups and dictionaries, respectively. What the function actually receives is a tuple args and a dictionary Kwargs, which is automatically converted internally as follows:

A, b, C = args

D = Kwargs (' d ', d_default_value)

E = Kwargs (' e ', e_default_value)

As in the following example:

In [Argsfunction]: def (*args, **kwargs):
    ...:     print (' args is ', args)
    ...:     print (' Kwargs is ', Kwargs ) ...
    :     print (' args is ', args[0]) ...
    :     print (' key ' kw1\ ' value is ', Kwargs.get (' kw1 ', ' Java ')
    ...: in

[[+]: argsfunction (2, 4, kw1= ' thon ', kw2= ' py ') args is  (2, 4) Kwargs is  {' Kw1 ': ' Thon ', ' kw2 ': ' py '}, ' a ', ' the ', ', ', ', ', ', '

3, Corrie: Part of the application of parameters

The technique of deriving a new function from an existing function by using "Partial parameter Application", as in the following application:

In [Panax]: def add_number (x, y):
    ...: return     x+y ...
    : in

[): Add_five = Lambda y:add_number (5, y) 
  in [$]: print (add_five)
15

The second parameter of Add_number is called "Gerty", whose essence is to define a new function that can invoke an existing function . The built-in functools module can simplify this process with the partial function . As shown below:

In [1]: def add_numbers (x, y):
   ...: return     x + y;
   ..: in

[2]: from functools import partial into

[3]: Add_six = partial (add_numbers, 6) in

[4]: Print (Add_six (10) )
16

4, Generator

A builder (generator) is a simple way to construct a new, iterative object , which returns only a single value after a general function executes, and the generator returns a sequence of values in a deferred manner , that is, Pauses after each value is returned until the next value is requested. to create a builder, simply replace the return in the function with yield , and see the following example:

In [5]: #函数 in

[6]: def squares1 (n=10):
   ...:     print (' generating squares from 1 to%d ' (n * * 2))
   ...:     For I in range (1, n+1):
   ...: return         i * * 2 ...
   : in

[7]: sq1=squares1 ()
generating squares from 1 to 10 0
In [8]: #生成器 in

[9]: def squares2 (n=10):
   ...:     print (' generating squares from 1 to%d ' (n * * 2))
   ...:     for I in range (1, n+1):
   ...:         yield i * * 2
   ...: In [a

]: gen = Squares2 () in [one

]: gen
OUT[11]: <generator object squares2 at 0x000001f35699d8e0> in

[a]: for X in Gen:
    ...:     print (x) 
  :
generating squares from 1 to
1
4
9
81
100

Builder expression (generator expression): Is the simplest way to construct a builder, and the generator also has a list, dictionary, and Collection derivation, created by: Change the square brackets (brackets) at both ends of the list to parentheses (parentheses), as follows:

(x * * * 2 for X in range ())

in [/]: Gen2
out[14]: <generator object <genexpr> at 0x000001f356a92ca8>

The builder expression can be used in any Python function that accepts a generator , as follows:

in [[]: Sum (x * * 2 for X in range ())
out[15]: 328350

itertools module: standard Library The Itertools module has a set of generators for common data algorithms, such as GroupBy can accept any sequence and a function , which is based on the return value of the function continuous elements are grouped (note is a continuous element), the following example:

in [[]: #itertools模块
    ...: Import itertools ...
    : First_letter = lambda x:x[0]
    ...: names=[' Alan ', ' ABC ', ' Test ', ' Tom ', ' ACT ', ' Why ']
    ...: For letter, names in Itertools.groupby (names, first_letter):
    ...:     print (Letter, list (names))
    ...:
a [' Alan ', ' ABC ']
T [' Test ', ' Tom ']
a [' ACT ']
W [' Why ']

the common itertools functions are as follows:

(1) IMAP (func, *iterables): A builder version of the built-in function map, which applies the func to each packaged tuple of the parameter sequence;

(2) IFilter (func, iterable): Generator version of built-in function filter, output element x when func (x) is true;

(3) combinations (iterable, K): Generates a sequence of all possible K-tuples in iterable (regardless of order);

(4) permutations (iterable, K): Generates a sequence of all possible K-tuples in iterable (consideration order);

(5) GroupBy (iterable[, Keyfunc]): Generates one (key, Subitrator)for each unique key.

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.