Python built-in functions (continuous update) and lambda expressions

Source: Internet
Author: User
Tags iterable numeric value unpack

Python has a lot of built-in functions, and it helps to be flexible. This article currently includes: Slice () set () round () map () Zip () filter () reduce () (not built, belonging to the Functools Library) sorted ()

It is worth noting that after Python3 , the map (), zip (), filter () returns the object is no longer a list , but an iterator .
iterators are very important in Python , and in doubt you can see:
Analysis of the use of Python yield
Iterables vs. Iterators vs. generators


slices

Slicing is a good helper when we need to intercept the list or get its reverse order.

>>> L = [0, 1, 2, 3]
>>> l[:]
[0, 1, 2, 3]
>>> l[2:]
[2, 3]
>>> L[:3]
[0, 1, 2]
>>> l[::-1]
[3, 2, 1, 0]
>>> l[-1:-2:-1]
[3]

The syntax is R = l[i:j:s] here we explain the meaning of these parameters:

Letters meaning Description
S Step The default is 1
I Start element position When s>0, the default is 0, when s<0, the default is-1
J Terminates the element position (not including the element, that is, [I, J)) When s>0, the default is Len (r), when s<0, the default is-len (r)-1


The corresponding is the built-in function slice ()

>>> Myslice=slice (0,2)
>>> myslice
Slice (0, 2, None)  # correspond respectively [I, J, S]
>>> l[ Myslice]
[0, 1]


Set Operations

>>> before = [0, 1, 2]
>>> after = [1, 2, 3]
>>> print (list (set (before) & (set Afte R)))
[1, 2]
>>> list_union = List (set (before) | (Set (after)
) >>> list_union
[0, 1, 2, 3]
>>> add_items = List (set (list_union)-(set (before))
> >> Add_items
[3]
>>> del_items = List (set (list_union)-(set (after))
>>> DEL_ Items
[0]

This brings us to the two list detailed differences.
The set () function can create a set of unordered and distinct elements that can be tested for relationships, delete duplicate data, and compute intersections (&), Difference sets (-), and set (|). Wait


precision control of floating point numbers

Generally we use the round () function to control the floating-point precision.

>>> Round (1.1)
1
>>> round (1.12, 1)
1.1
>>> round (1.123, 2)
1.12

The first argument is a floating-point number, and the second argument is a reserved scale, optional, and left to an integer by default if not written.
If there is a requirement for precision after interception, join the following link:

A little pit in Python about the round function
Why does Python not solve rounded (round) "Bugs"?


Data Filtering (filter)

Use Help (filter) to view official documents:

Class Filter (object)
 |  Filter (function or None, iterable)--> Filter Object
 |  
 |  Return a iterator yielding those items of iterable for which function (item)
 |  Is true. The If function is None and return the items that are true.

Example:

>>> List (filter (lambda x:x > 2, [0, 1, 2, 3]))
[3]
>>> list (None, [0, 1, 2])
[1, 2]


map ()

The map () can process data in batches, and input can be more than one iteration object compared to filter ()

Class Map (object)
 |  Map (func, *iterables)--> Map Object
 |  
 |  Make a iterator that computes the function using arguments from
 |  Each of the iterables.  Stops the shortest iterable is exhausted.

Example:

>>> list (map (Lambda x:x * 2, [1, 2, 3]))
[2, 4, 6]

# When more than one iteration object, the parameter and iteration object are in order one by one corresponding    
# when two iterations are not as long, the shortest primary 
  >>> list (lambda x: [x * 2, X + 1], [1, 2, 3])
[[2, 2], [4, 3], [6,]]
>>> list (lam BDA x, y: [xy, X + y], [1, 2, 3], [3, 2, 1, 0])]    
[[-2, 4], [0, 4], [2, 4]]
>>> def add (x, y):
. .     return x + y
... 
>>> List (map (add, [1, 2, 3], [3, 2, 1, 0]))
[4, 4, 4]      

# type conversion
>>> list (map (int, "1234")) 
  [1, 2, 3, 4]

The above is only part of the flexibility to use can have greater use.


Package Unpack (Zip)

Official documents:

Class Zip (object)
 |  Zip (iter1 [, Iter2 [...]])--> Zip object
 |  
 |  Return a Zip object whose. __next__ () method returns a tuple where
 |  The i-th element comes from the i-th iterable argument.  The. __next__ ()
 |  Method continues until the shortest iterable in argument sequence
 |  is exhausted and then it raises stopiteration.


You can package the item under the same index for multiple iteration objects into a tuple.
Example:

>>> list Zip ([1, 2, 3], [1, 2, 3])) [(1, 1), (2, 2)
, (3, 3)]
>>> list (Zip ([1, 2, 3, 4], [1, 2, 3]))
[(1, 1), (2, 2), (3, 3)]
# Use * can unpack
>>> list (*[(1, 1), (2, 2), (3, 3)))
[(1, 2, 3 ), (1, 2, 3)]

# Use ZIP to construct map
>>> key = [1, 2, 3]
>>> value = ["A", "B", "C"]
>&G T;> dict (Zip (key, value))
{1: ' A ', 2: ' B ', 3: ' C '}


reduce ()

Handles each item of the iteration object, drawing a value that can be a numeric value or a list.

Reduce (...)
    Reduce (function, sequence[, initial])-> value

    Apply a function of two arguments cumulatively to the items of a SEQ Uence, from left
    to right, and so as to reduce the "sequence to" a single value.
    For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates ((((1+2) +3) +4)
    .  If Initial is present, it is placed before the items
    to the sequence in the calculation, and serves as a default The
    sequence is empty.
# Special NOTE:  function has and has only two parameters. Initial is the initialization value, and if so, the first operation is computed with this value and the 
first value in # sequence, and if not, it is computed with the top two values of sequence. The calculated value is then computed in
sequence with the value of sequence #, and the result is finally obtained.


Example:

# ((1 + 2) + 3) + 4)
>>> Reduce (lambda x, y:x + y, [1, 2, 3, 4])
>>> Reduce (lambda x, Y:x + y, [2, 3, 4], 1)
>>> Reduce (Operator.add, [2, 3, 4], 1)
# sequence is empty time
>> > Reduce (Operator.add, [], 1)
1
# list addition
>>> reduce (Operator.add, [[1, 2]],  [2, 3, 4]) C12/>[2, 3, 4, 1, 2]


lambda expression

Why there are lambda expressions. Or which occasions apply to lambda expressions.
1, function simple, only a few lines, using lambda expression clear;
2, the function is only called a few times, specifically write a function, "pollution namespace"

We've used lambda expressions above, so let's make it work with sorted to achieve a variety of high difficulty sorts.
Note: Dict key is implemented in hash, it is disorderly, but we can get sorted by rules after its key value list, according to the list order can be sorted after the Dict

Reference: Python: Use lambda to sort various complex situations, including list nesting dict

Let's look at the sorted () function:

Sorted (iterable, Key=none, Reverse=false) return
    A new list containing all items from the iterable in ascending order.

    A Custom key function can is supplied to customize the sort order, and the
    reverse flag can is set to request the result in descending order.

Example:

# each alphabetical order of strings >>> sorted ("abc") [' A ', ' B ', ' C '] # alphabetical order >>> sorted (["B", "C", "A"]) [' A ', ' B ', ' C '] >>> sorted (["B", "C", "a"], reverse=true) [' C ', ' B ', ' A '] # Dict sorted by key, output key list >& gt;> dic = {1: "B", 3: "A", 2: "C"} >>> sorted (DIC) [1, 2, 3] # Dict sorted by value, output key list >>> sorted (di C, Key=lambda K:dic[k]) [3, 1, 2] # list nested list >>> lis = [[1, 2, 3], [1, 2, 4], [2, 1, 1]] >>> sort Ed (LIS) [[1, 2, 3], [1, 2, 4], [2, 1, 1]] # list nested dict >>> lis = [{' name ': ' John ', ' Score ': ten}, {' name ': ' Dick ' , "Score": 8}, {"Name": "Harry", "Score": one}] >>> sorted (LIS, Key=lambda x:x["Score"]) [{' Name ': ' Dick ', ' Score ': 8}, {' name ': ' John ', ' Score ': ten}, {' name ': ' Harry ', ' Score ': one}] 

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.