Python Automation Development Learning 3-2-anonymous functions, built-in functions

Source: Internet
Author: User
Tags abs ord pow vars

anonymous functions

If the function value is used once and the structure statement (which requires a single line of expression), an anonymous function can be used. Benefits of anonymous functions:

    1. The program is used once, so there is no need to define the function name and save the variable definition space in memory.

    2. Make the program more concise

Common functions:

def test (x, y): return x+yprint (Test)

Anonymous functions:

Test = Lambda x,y:x+yprint (test)

Lambda: Defining an anonymous function

Colon (:): Delimiter

Part before colon: parameter of function, can have no argument, but colon cannot save

The part after the colon: The return value of the function. Lambda has no return, followed by a return value

In the above case, we still set a variable name, because it is convenient to assign a value to the parameter later, so that the function does not free up space after it is exhausted. Enclose the entire function, followed by a parenthesis to write the parameter.

Print ((lambda x,y:x+y))

Eventually it becomes a line, which is much like functional programming.

Give an example of the maximum value:

f = (Lambda x,y:x if x>y else y) print (f (2,3)) print (f (6,4))

But the above example doesn't usually have to be written like this. This is not normally used because anonymous functions are used in conjunction with other functions, such as reduce, filter.

A = filter (lambda x:x>3,[1,2,3,4,5,6,7,8,9]) # filter elements in list by lambda function print (list (a))

Nested use

Anonymous functions can be nested in normal functions, and the anonymous function itself acts as the return value of a return.

def func (n): return lambda x:n**xf = func (3) Print (f (2), F (3), F (4))

Built-in functions

And then all of the built-in functions are told again, not all, many of the objects of the class are skipped first.

ABS () take absolute value

Print (ABS (3), ABS (0), ABS (-4))

All () An iterator object that returns true if all values are true

Print (All ([0,1,2,3,4,5]) # Falseprint (All ([1,2,3,4,5])) # True

Any () an iterative object returns true only if one of the values is true

Print (Any ([0,1,2,3,4,5]) # Trueprint (Any ([0, ', False,none])) # False

ASCII () turns an object into a printable form of a string, which is useless.

Print (Type (123), type (ASCII (123)), ASCII (123)) # int type by ASCII () becomes STR type print (ASCII ("Hello")) # The text will also transcode

Bin () converts an integer into binary

Print (Bin (8)) # 0b1000

BOOL () Boolean to determine true or false

Print (bool (1)) print (bool ([))) Print (Boolean ([i])) print (bool ("Hello")) print (bool (None))

ByteArray () becomes a bytearray format

Bytes () becomes a bytes format

A = bytes ("ABCDE", encoding= "Utf-8") b = ByteArray ("ABCDE", encoding= "Utf-8") print (Type (a), type (b)) #a [1] = 99 # Bytes Type is not modifiable, str type is also b[1] = 99 # This can be modified by print (A, B)

Callable () Determines whether an object can be called. After the function name can be added (), plus () is called. Whether it can be called, or whether it can be added later ()

A = []print (callable (a)) # Fales, List cannot be called Def b (): Passprint (callable (b)) # True, function can be called C = (I for I in range) PRI NT (callable (c.__next__)) # True, generator C can invoke next element with Next method

Chr () returns the character corresponding to this integer

Ord () returns the encoding of the character corresponding to this character

Print (CHR) print (ORD ("D")) Print (Chr (8364)) # Is this symbol print (Chr (7)) # This will make a beep

Classmethod (function) class method, which will be spoken later

Compile () compiles the code, presumably. We didn't use it to give a demo that we could perform.

Compiles the code in the form of a string.

#  turn your code into a string that exists in the variable code =  "" "Def fib (n):     i,a,b = 0,0,1     while i < n:         #print (b )         yield b        a ,b = b,a+b        i += 1     return  "End" F = fib (Ten) while 1:    try:         x = next (f)   # x = f.__next__ ()          print (x)     except StopIteration as e:         print ("Return value is:", E.value)          Break "" "#exec (code)   #  actually here Direct exec is also possible to execute Py_obj = compile (code," "," exec ")   #   Compile your code, the second parameter is the file name to store the compilationThe error message in the process exec (py_obj)   #  above is edited with Exec, where exec executes 

This example is not very good, the sentence above the comment out of the statement directly executed is also possible, do not need to be compiled by compile. But there is no other example, in short, is not used

Why is exec here, what is exec, or can it be anything else, for the time being don't know.

Complex () to generate complex numbers

A = Complex ("1+2j") # string converted to complex print (type (a), a) b = complex # Two parameters are numbers, the first one is real, the second is the imaginary part print (type (b), B)

Delattr () was skipped over and will speak later

Dict () creates dictionaries that can actually be used to generate very complex dictionaries, such as a list to construct

A = Dict () # Create an empty dictionary print (type (a), a)

Dir () See how the object is

A = {}print (dir (a)) B = "123" Print (dir (b)) c = 123print (dir (c))

Different data types, the method that can be used is not. Two __ underline is the internal method, generally can not be used, but also can be used, such as the __next__ of iterators.

Divmod (A, A, a, b), a divided by the quotient and remainder

Print (Divmod (9,5)) # (1,4) print (Divmod (10,4)) # (2,2)

Enumerate () can be a sequence of production indexes such as tuples or lists

List1 = [' A ', ' B ', ' C ', ' d ', ' E ']for i,j in Enumerate (list1): Print (I,J)

Eval () Converts a dictionary, list, and so on as a string into a corresponding data type

A = "{' A ': 1, ' B ': 2, ' C ': 3}" Print (Type (a), a) b = eval (a) print (type (b), B)

EXEC (), can execute code in string form

Comm = "" "A = [1,2,3,4,5]for i in A:print (i)" "" Exec (Comm)

Filter (), the parameter 2 is filtered according to the function of parameter 1

Map (), the parameter 2 is processed according to the function of parameter 1

Res1 = filter (lambda n:n>6,range) for I in Res1:print (i) Res2 = map (lambda N:n*2,range) for J in Res2:prin T (j)

Frozenset (), creating an immutable collection

A = set ([1,2,3,4,5]) A.pop () # The set can add or remove elements from print (type (a), a) b = Frozenset ([1,2,3,4,5]) #b. Pop () # Frozenset cannot change the inside element print (type (b), B)

Globals (), returns the variable name and value of the global variable, in the form of a dictionary. Local variables can be used with locals ()

Print (Globals ())

GetAttr (), returns the object property value, about the object has not been mentioned, later will say, should be very important content

Hasattr () to determine if the object contains this property

SetAttr (), sets the object property value, and corresponds to the getattr above.

Hash () to get a hash of a string or numeric value

Print (hash (123)) Print (hash (' 123 ')) Print (hash (' Test ')) print (hash ([[)]) # List No, you need to convert to a string

Help (), view assistance

Help (' hash ') # to see the hash function's helper a = [] # A is now a list help (a) # View list

Hex (), turn the number into 16 binary

Print (hex) print (Hex (1023)) Print (Hex (-256))

ID (), Return memory address

Def a (): Passprint (a) # Here the direct print function of the memory address of print (Hex (ID (a))) # ID is 10 binary by default, turns into 16 binary and the same as above

Input (), gets the string entered

A = input ("Enter any string:") print (a)

Int (), turn to 10, the default input is 10, or the second parameter specifies

print (int (' 15 ')) # default 10 binary print (int (' 10 ', 16)) # 16 binary 10 is 10 binary 16print (int (' 0x10 ', 16)) # The instant string has 0x before it, and the subsequent 16 binary cannot omit print ( int (' FF ', +)) print (int (' 0b100 ', 2)) print (int (' 100 ', 5)) # There can also be strange binary, 5 binary print (int (' 1gg ', 17)) # 17 binary

Isinstance (), determine whether parameter 1 is the type of parameter 2

Print (Isinstance (1,STR)) # Falseprint (isinstance (' 1 ', str)) # Trueprint (Isinstance ([], (Set,dict))) # False, Whether it is one of the types of Yongzu print (Isinstance ([], (List,dict)) # True

Issubclass (), is not a subclass. What is class, not yet learned

ITER (), replace with an iterator

From collections Import Iteratora = [1,2,3,4,5,6] # A is the list print (Isinstance (a,iterator)) # Fales, now A is not an iterator B = iter (a) # Turn A into an iterator print (Isinstance (b,iterator)) # True, now B is an iterator with print (b.__next__ ()) # can be used with Nextprint (b.__next__ ()) Print (b.__ Next__ ())

Len (), return length

Print (Len (' 123 ')) print (Len ([+]))

List () to convert the meta-ancestor to a listing. As long as the iteration object should be able to

A = (a) b = List (a) print (type (a), a) print (type (b), b) print (range) print (List range) # range () can also go

Locals (), prints the local variable of the current position, the form of the dictionary, the variable name and the value

def test (): Local_var = 123 print (locals ()) # Print local variable, only one Local_var print (Globals ()) # Printing is still a global variable, local variable tes with no current position T () print (Locals ()) # This position prints the global variable print (globals ()) # printed or global variable

Map (), which maps the specified object according to the provided function

A = map (lambda x:x**2,[1,2,3,4,5]) # Each element in the list is computed with a lambda method for print (list (a))

Max () and Min (), returns the maximum and minimum values

Print (max) # can be several variable print (min ([+)]) # or it can be a list

Memoryview () that returns the memory view object for the given object (Momory view). Do not understand, also can not use.

Next (), call the next item of the iterator via __next__ ()

A = ((Lambda x:x**2) (i) for I in Range (2,10)) # constructs an iterator print (next (a)) # prints out the next item in the iterator print (next (a)) print (Next (a))

In the Object,python, everything is the object. As to what is the use of this place, do not know

Oct (), converting integers to 8 binary

Print (Oct (1)) Print (Oct (8)) Print (Oct (9)) Print (Oct (0xa)) # This is a 16-binary notation.

Open () opens the file. Used a lot before, slightly.

Ord (), before Chr () talked together

Pow (), exponentiation. In fact, there can be 3 parameters pow (x, y, z), which is calculated (X**y)%z, with Z in the case of the remainder.

Print (POW (2,10,3) # 2**10 divided by 3 remainder of print (POW (2,10)) # 2 for 10 power

Print (), slightly

Property (), returns the new Class attribute, which will be spoken later.

Range (), see example directly

Print (list (range 10)) # 1 parameters, starting with 0 print (List range (2,10)) # 2 parameters: Specify start and end print (List range (2,10,2)) # 3 parameters: Plus step

Repr () to convert the object to a string

A = [1,2,3,4,5]b = repr (a) print (type (a), a) # A is the list print (type (b), b) # B is a string

Reversed (), reverses the object, returns an iterator

A = (1,2,3,4,5) b = Reversed (a) print (next (b)) print (list (b)) c = [' A ', ' B ', ' C ', ' d ', ' e ']d = reversed (c) print ( List (d))

Round (), formats the floating-point number. The first parameter is a numeric value, and the second parameter is the number of decimal digits. %f with string formatting should be more convenient, but if you want to control the number of decimal digits with a parameter, you should only rely on round ()

Print (Round (0.1234,2)) num = 0.1234567for i in range (3,7): Print (Round (num,i))

Set (), create collection

A = [1,2,3,4,5,2,3]B = set (a) print (type (b), B)

SetAttr (), sets the object property value, and corresponds to the getattr above. This is very important and will be spoken later.

Slice (), slice. General use [x:y:z], so useless

arr = Range (Arr[slice (2,8,2)) print (Arr[2:8:2]) # Same as above effect

Sorted (),

A = {' C ': 5, ' Z ': 2, ' a ': 4, ' O ': 9, ' f ': 8}b = sorted (A.items ()) # by Dictionary key to sort C = sorted (A.items (), Key=lambda x:x[1]) # by Dictionary of value Sort more complex Print (a) # The original dictionary print (b) # after sorting, but here is the list, because the dictionary is unordered print (c) # After sorting, according to the original dictionary value output

B=sorted (A.items (), Key=lambda x:x[1]) This sentence explains. The second parameter of sorted is the keyword that specifies the sort. The key= here is the key parameter of the sorted function (not the dictionary key), which is sorted by the value of Lambda x:x[1]. This has turned every element of the dictionary into a tuple, referring to the output of B. Here X[1] is the second element of the tuple, which is the value of the dictionary. So it is sorted by the value of the dictionary.

Staticmethod (), is a method that will be spoken later.

Str (), converted to a string.

SUM (), sum

Super (), a very important object-oriented concept of inheritance, also to be talked about later.

Tuple () to generate a tuple

Type (), view data type

Print (Type (1)) Print (Type (' 1 ')) print (Type (True)) print (type ({})) print (type ([])) Print (Type (()))

VARs () returns all the property names and values of an object, and the default parameter is the same as locals (). Adding objects has a different effect. However: 1, the object has not learned, 2, or not to use

Class runoob:a = 1def Test (): a = 1 print (VARs ()) print (locals ()) print ("2 effects inside function") test () print ("Action on Global, 2 effects Still the same ") print (VARs ()) print (locals ()) print (" VARs can take parameters, specify a class, primarily this function ") print (VARs (Runoob))

Zip (), which combines several iterative objects.

A = [1,2,3,4]b = [' A ', ' B ', ' C ', ' d ']for i in zip (b): # Combine two iterations of the object print (i) c = [' A ', ' B ', ' C ', ' d ', ' E ']for i in zip (a,c) : # If the length is different, press short to print (i) for I in Zip (a,b,c): # Number of parameters indefinite print (i)

__import__ (), dynamically loaded. The general load module with import is good. If a module changes frequently it is necessary to use __import__ () to dynamically load. May be used in the future. Just know for a moment.

Python Automation Development Learning 3-2-anonymous functions, built-in functions

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.