6.3. High-order functions, common built-in functions, and 6.3 Built-in high-order functions

Source: Internet
Author: User
Tags iterable

6.3. High-order functions, common built-in functions, and 6.3 Built-in high-order functions
Higher-order functions:

  • You can pass a function as a parameter to another function;
  • Returns a function.
# The return value is the function sum = lambda x, y: x + ysub = lambda x, y: x-ycalc_dict = {"+": sum ,"-": sub} def calc (x): return calc_dict [x] print (calc ('-') (5, 6) print (calc ('+') (5, 6 )) # Function filter with function parameters (lambda x: x> 5, range (20 ))
Common built-in functions:
  • Abs (x): returns the absolute value.
  • Range ([start], stop [, step]): generates a sequence, starting from 0 by default.
    • Note: The returned result is not a list object.
>>> Print (range (20) range (0, 20) >>> type (range (20 )) <class 'range' >>> isinstance (range (20), Iterable) ######### it is an iteratable object True >>>> from collections import Iterator >>>> isinstance (range (20), Iterator) # Not An iterator object, False
  • Oct (x)
    Convert a number to an octal number.
  • Hex (x)
    Convert integer x to a hexadecimal string
  • Bin (x)
    Convert integer x to a binary string
>>> oct(8)'0o10'>>> hex(8)'0x8'>>> bin(8)'0b1000'
  • Chr (I): returns the Unicode Character corresponding to the integer I.
  • Ord (x): converts a character to a corresponding Unicode addressing.
>>> Ord ('中') 20013 >>> chr (20013) '中'
  • Enumerate (sequence [, start = 0]): returns an enumerated object. The next () method of this object returns a tuple
for i, value in enumerate(['A', 'B', 'C']):    print(i, value)
  • Iter (o [, sentinel]): generates an object iterator. The second parameter represents the delimiter.
From collections import Iterator # the object that can be called by the next () function and continuously return the next value is called the Iterator: Iterator. Print (isinstance ([], Iterator) print (isinstance (iter ([]), Iterator ))
    • Sorted (iterable [, cmp [, key [, reverse]) sorts iterated objects.
    >>> l=[8,7,6,5,4,3,2,1]>>> sorted(l)[1, 2, 3, 4, 5, 6, 7, 8]
      • Cmp (x, y): returns a negative number if x <y; x = y, returns 0; x> y, returns a positive number.
        • All (iterable)
          1. All elements in the iteratable object are true.
          2. In particular, if the iteratable object is null, True is returned.
        >>> l=[]>>> all(l)True>>> l=[1,2,3,4,5]>>> all(l)True>>> l=[1,2,3,4,5,0]>>> all(l)False
          • Any (iterable)
            1. The element in the iteratable object is true when it is true.
            2. In particular, if the iteratable object is null, False is returned.
          >>> l=[]>>> any(l)False>>> l=[0,0,0,0]>>> any(l)False>>> l=[0,0,0,0,5]>>> any(l)True>>>
          • Eval (expression [, globals [, locals]): calculates the value of expression.
          >>> str1="3+4">>> eval(str1)7
          • Exec (object [, globals [, locals]): executes the Python statement stored in a string or file.
          >>> str1="print('hello world')">>> exec(str1)hello world
            • Compile (source, filename, mode [, flags [, dont_inherit])
              • Compile source as a code or AST object. Code objects can be evaluated using exec statements or eval.
                1. Parameter source: string or AST (Abstract Syntax Trees) object.
                2. filename: name of the code file. If the code is not read from the file, some identifiable values are passed.
                3. Parameter model: specifies the type of the compiled code. You can specify it as 'exec ', 'eval', and 'singles '.
                4. Parameters flag and dont_inherit
            str1 = "print('hello world')"c2 = compile(str1,'','exec')   exec(c2)str2="3+4"c3=compile(str2,'','eval')a=eval(c3)print(a)
                      • Id (object): The function is used to obtain the memory address of an object.
                      >>> id(str1)1514678732384>>> str2=str1>>> id(str2)1514678732384
                          • Isinstance (object, classinfo): determines whether the object is a class instance.
                          >>> isinstance(1,int)True>>> isinstance(1.0,int)False
                              • Len (s): Return length (number of bytes returned in ascll format, number of characters returned in unicode/or number of elements)
                              >>> A = B 'abc' >>> len (a) 3 >>> B = "I love China" >>> len (B) 4 >>> c = [1, 2, 3, 4] >>> len (c) 4
                                  • Repr (object): converts an object to a string format that can be read by the interpreter.
                                  >>> c=[1,2,3,4]>>> repr(c)'[1, 2, 3, 4]'>>> d={1:2,2:3,3:4}>>> repr(d)'{1: 2, 2: 3, 3: 4}'
                                      • Type (object): type of the object returned
                                      >>> type(1)<class 'int'>>>> type("123")<class 'str'>>>> type((1,2,3))<class 'tuple'>

                                      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.