04_ built-in function (ii)

Source: Internet
Author: User
Tags define function

Built-in Functions (ii) 1.1 callable ()

Function: Whether the function can be called

Example 1:

Def f1 ():    passf1 () F2 = 123f2 () # Output result typeerror: ' int ' object is not callable

Example 2:

Def f1 ():    pass# f1 () F2 = 123# F2 () print (callable (F1)) print (callable (F2)) # output result TrueFalse
1.2 Chr ()

Function: Digital to letter, return the corresponding ASCII code.

R = chr (+) print (r) # output result A
1.3 Ord ()

Function: Letter to Number

n = Ord ("B") print (n) # output 66
1.4 Range ()

Function: Range of values

Example 1: Randomly generated 6-bit CAPTCHA letters

# before using, you must import Randomimport  random# define an empty list Li = []# loop 6 times, value range 6 bit for I in range (6):    # Set random number range 65-91    temp = Random.rand Range (p, p)    # The generated number is converted to the letter     C = chr (temp)    # Adds the resulting results to the list Li inside    li.append (c) # li = ["C", "B", "a"  ] #cba  Merge # stitching string joinresult = "". Join (LI) # Print results printed (result)

Example 2: Random 6-bit Verification code full version letter + number

# before using, you must import Randomimport  random# define an empty list Li = []# loop 6 times, value range 6 bit for I in range (6):    # Set R to Random generation, range 0-5    r = Random.ran  Drange (0, 5)    # when r=2 or r=4 if    r = = 2 or r = = 4:        # num is 0-10 randomly generated        num = Random.randrange (0, ten)        # Add num value to list        li.append (str)    # when r=0,1,3,4    else:        # temp is a A-Z random number 65-91        temp = Random.randrange (+)        # conversion Gets the number to the letter        C = chr (temp)        # Add letter to List        li.append (c) # li = ["C", "B", "a"]  #cba  Merge # stitching string joinresult = "". Join (LI) # Print results printed (result)
1.5 Compile ()

Function: Compiling a string into Python code

# single Line # eval expression # exec pythons = "Print (123)" # Compile string into Python code r = Compile (s, "<string>", "exec") # Execute code exec (r) # lose Results 123
1.6 eval ()

Function: Executes an expression, gets the result, has a return value

s = "8*8" ret = eval (s) print (ret) # output 64
1.7 exec ()

Function: Execute python code, receive code or string, no return value

EXEC ("7+9+8")

Summary: Compile,exec,eval

Compile (): Convert, string, compile into Python code
Eval (): Executes an expression, gets the result, has a return value
EXEC (): Execute Python code with no return value

1.8 Dir ()

Features: Quickly see what features an object provides

# The View list provides which features print (DIR (list)) # output results [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr__ ', ' __delitem__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ', ' __getitem__ ', ' __gt__ ', ' __hash__ ', ' __iadd__ ', ' __ Imul__ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __mul__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ ' Ex__ ', ' __repr__ ', ' __reversed__ ', ' __rmul__ ', ' __setattr__ ', ' __setitem__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook_ ' _ ', ' Append ', ' clear ', ' copy ', ' Count ', ' extend ', ' index ', ' Insert ', ' pop ', ' remove ', ' reverse ', ' sort ']
1.9 Help ()

Features: View Help, feature details

1.10 Divmod ()

Function: Compare x, Y, return quotient and remainder, return type is tuple

Example: Total: 97, each page shows 10, how many pages need

R = Divmod (97,10) print (r) # Output results (9, 7) 
1.11 Isinstance ()

Function: Used to determine whether an object is an instance of a class

# object is an instance of class S = "Alex" R = isinstance (S, str) print (r) # output True
1.12 Filter ()

Function: Used to filter some elements in a list

Format: Filter (function, object that can be iterated)

Example: Li = [11, 22, 33, 44, 55,], filtering for more than 22

1.12.1 writing functions
# define function F1def F1 (args):    # Set Empty list    result = []
# for loop for item in args: # To determine if item is greater than $ if item >: # greater than 22 added to result list Result.append (item) # Returns the result value return Resultli = [11, 22, 33, 44, 55,]# execute function ret = f1 (LI) print (ret) # output [33, 44, 55]
1.12.2 Filter function
# define function F2def F2 (a):    if a >: return Trueli = [One, three, three, seven, three,        ]# filter Inner Loop The second parameter, let each loop element execute the function if the function's return value Tru E, element legal ret = filter (F2, Li) print (list (ret)) # output result [33, 44, 55]
The 1.12.3 is implemented with a lambda expression

Lambda Review Auto return

F1 = Lambda a:a > 30ret = f1 (All) print (ret) # implements filtering, simplified expression li = [one, one, a, a, a, a,]result = filter (lambda  a:a > , Li) Print (list result) # output [33, 44, 55]
1.13 Map ()

Function: Map a list to another list

Format: Map (function, iterative object (something that can be looped))

example, the number of tables in the list increased by 100 respectively

Map method

# list li = [11, 22, 33, 44, 55,]# define function F2, parameter adef F2 (a):    # function body, a + 100 and return value returns    A + 100# run function, all elements in Li list loop as parameters of F2 function A and execute Fresult = Map (F2, Li) print (list result) # output [111, 122, 133, 144, 155]

Lambda method

Li = [111, 122, 133, 144, 155]]result = map (lambda a:a + P, Li) print (list result) # output
1.14 globals (), locals ()

Globals all global variables

Locals all local variables

NAME = "ALEX"  # global Variable def show ():    a = 123  # local variable    c = 123    print (Globals ())    print (Locals ()) show () # Output result # global variable {' __cached__ ': None, ' __name__ ': ' __main__ ', ' __package__ ': None, ' __loader__ ': <_frozen_importlib_ External. Sourcefileloader object at 0x000000db870c5940>, 'NAME ': ' ALEX ', ' show ': <function show at 0x000000db8712e510>, ' __file__ ': ' old_dict.__delitem__ (host) \n\nprint (u "= = Information updated = =") \nprint (old_dict) \ n '} # local variable {' A ': 123, ' C ': 123}
1.15 Hash ()

Function: Convert hash value, commonly used to save key in dictionary

s = "FFFF" Print (hash (s)) # output 6225191154271087305
1.16 Len ()

Function: Character length

Python 3 default by character ()

s = "Li Jie" print (len (s))

python2.7 by default in bytes

s = "Li Jie" b = bytes (s, encoding= "Utf-8") print (len (b))
1.17 sum ()

Function: the addition of elements in a sequence of numbers

r = SUM ([11,22,33,44,]) print (r) # output 110
1.18 Memoryview ()

Description: A class of memory address-related

1.19 Object ()

Description: Is the parent class of all classes

1.20 Pow ()

Function: Method returns the value of XY (x's y-square)

# need to import Mathimport Mathprint (Math.pow (2, 3)) # Output Result 8.0
1.21 Property ()

Description: Attributes (object-oriented)

1.22 repr ()

Function: __repr__ in repr execution class

r = repr ("Alex") print (r) # output result ' Alex '
1.23 Reversed ()

Function: Invert

Print (List (reversed ([' NB ', ' is ', ' Alex ')]) # output results [' Alex ', ' is ', ' NB ']
1.24 round ()

Function: Rounding

Format: Round (number, reserved digits)

Print (Round (5.44, 1)) Print (Round (5.77, 1)) # output result 5.45.8
1.25 Slice ()

Features: Slicing

s = "Sssssssss" Print (S[0:2:2]) # output result s
1.26 sorted ()

Function: Sort

Li = [11, 44, 22, 33][11, 22, 33, 44] 33,]print (LI) li.sort () print (LI) # output results
1.27 Zip ()

Function: Accepts a series of iterated objects as parameters, packages the corresponding elements in the object into tuple (tuples), and returns a list of these tuples

L1 = ["Alex", one, one, one,]L2 = ["is", one, one, one,]l3 = ["NB", one, A, a,]r = Zip (L1, L2, L3) # Print (list (r)) temp = Lis T (r) [0]ret = "". Join (temp) print (ret) # Output results Alex is NB

  

04_ built-in function (ii)

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.