Python built-in functions and anonymous functions

Source: Internet
Author: User
Tags ord pow

built-in functions

68 built-in functions. They are all the functions that Python gives you to use directly.

built-in Functions
ABS () Dict () Help () Min () SetAttr ()
All () Dir () Hex () Next () Slice ()
Any () Divmod () ID () Object () Sorted ()
ASCII () Enumerate () Input () Oct () Staticmethod ()
Bin () Eval () Int () Open () STR ()
BOOL () EXEC () Isinstance () Ord () SUM ()
ByteArray () Filter () Issubclass () POW () Super ()
Bytes () Float () ITER () Print () Tuple ()
Callable () Format () Len () Property () Type ()
Chr () Frozenset () List () Range () VARs ()
Classmethod () GetAttr () Locals () Repr () Zip ()
Compile () Globals () Map () Reversed () __import__ ()
Complex () Hasattr () Max () Round ()
Delattr () Hash () Memoryview () Set ()

The table above is the built-in function, and 68 functions are here. The Order of the table is in the order of the first letter, and you will find all the clutter stacked together. For example, the Oct and bin and hex are all binary conversions, but they are written in three places ... This is very bad for everyone to summarize and learn. Then I divide these functions into 6 categories. Here's a picture.

Mind Map Address: https://www.processon.com/view/link/597fcacfe4b08ea3e2454ece

Password g76z

Scope-dependent

Get local variables and global variables in dictionary-based form

Globals ()--Get a dictionary of global variables

Locals ()--Gets a dictionary of local variables within the namespace where this method is executed

Other

Execution of String type code

Http://xxxxx

Input/output Related:

Input () inputs

s = input ("")  # Enter content assigned to s variable print(s)  # Enter what prints what. Data type is str
usage of input

Print () output

def Print (Self, *args, sep=', end='\ n'#  Known special case of print< /c8> "" "        Print (value, ..., sep= ', end= ' \ n ', File=sys.stdout, flush=false)    file: The  default is output to the screen, if set to file handle, output to file    Sep:   Print separators between multiple values, default to Space    end:   Each time the end of the print, the default is the line break    flush: Immediately output the content to the stream file, do not    cache "" "Print Source Analysis
Print Source Profiling
f = open ('tmp_file','w')print(123,456, sep=',', file = f,flush=true)
description of the file keyword
Import Time forIinchRange (0,101,2): Time.sleep (0.1) Char_num= I//2#print How many ' * 'Per_str ='\r%s%%:%s\n'% (I,'*'* Char_num)ifi = = 100Else '\r%s%%:%s'% (I,'*'*char_num)Print(per_str,end="', flush=True)#Little Yue: \ r You can move the cursor to the beginning of the line without wrappingPrint progress bar
Print progress bar

Data type correlation:

Type (o) returns the data type of the variable O

Memory-Related:

ID (o) o is a parameter that returns the memory address of a variable

Hash (o) O is a parameter that returns a hash value of a hash variable, and the non-hash variable will be hashed after the error.

T= (= = [n/a]print(hash (t))  # hashprint(hash (L))  # will error " Result: typeerror:unhashable type: ' list '" Hash instance
Hash Instance

The hash function processes the current hash variable according to an internal algorithm, returning an int number.

* Each time the execution of the program, the same content of the variable hash value will not change during this time of execution.

File Operation related

Open () Opens a file that returns a file operator (file handle)

The mode of operation of the file has a total of 6 r,w,a,r+,w+,a+, each of which can be operated in binary form (rb,wb,ab,rb+,wb+,ab+)

You can specify the encoding with encoding.

Module Operation related

__import__ Importing a module

Import Time
Import Module
__import__ ('os') Print (Os.path.abspath ('. '))
__import__

Help methods

In the console, perform help () to enter assist mode. You can enter variables or types of variables as you choose. Enter Q to exit

or directly execute Help (O), O is the parameter, view and variable o about the operation ...

and invoke related

Callable (o), O is the parameter to see if this variable is callable.

If O is a function name, it returns true

def func ():passprint(callable (func))  # parameter is a function name, callable, returns True  Print(callable (123))   # parameter is a number, not callable, returns false
Callable Instances

View all built-in methods for the type of the parameter

Dir () View the properties in the global space by default, and also accept a parameter to view the methods or variables within this parameter

Print (dir (list))  # View the built-in methods for a list Print (dir (int))  # to view the built-in methods for integers
view built-in methods for a variable/data type

and number-related

Number--Data type Related: Bool,int,float,complex

Number--Binary conversion correlation: Bin,oct,hex

Numbers-mathematical operations: ABS,DIVMOD,MIN,MAX,SUM,ROUND,POW

and data structure related

Sequence--Lists and tuples Related: list and tuple

Sequence--string-Related: Str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

ret = ByteArray ('Alex', encoding='utf-8')Print  (ret) print = Allprint(ret)print(ID (ret))
ByteArray
ret = Memoryview (bytes (' hello ', encoding='utf-8')) Print (len (ret)) Print (bytes (Ret[:3]). Decode ('utf-8')) Print (Bytes (ret[3:]). Decode ('utf-8'))
Memoryview

Sequence: Reversed,slice

L = (1,2,23,213,5612,342,43)print(l)print(list (Reversed (l)))
Reversed
L = (1,2,23,213,5612,342,43= Slice (1,5,2)print(L[sli])
Slice

Data collection--dictionaries and collections: Dict,set,frozenset

Data collection: Len,sorted,enumerate,all,any,zip,filter,map

Filter and map:#

Sorted Method: #

Anonymous Functions

Anonymous functions: A sentence function designed to address the simple requirements of functions

# this piece of code def Calc (n):     return n**nprint(calc# to anonymous function lambda n:n** N Print (Calc (10))

Above is our analysis of this anonymous function of Calc, and here is a description of the anonymous function format

Lambda parameters: Return value # arguments can have multiple, separated by commas # Anonymous functions No matter how complex the logic, can only write one line, and the end of the logical execution of the content is the return value # The return value can be any data type as well as a normal function

As we can see, anonymous functions do not really have names.

There is no difference between the invocation of an anonymous function and a normal invocation. is the function name (parameter) can be.

Practice a practice:

Please turn the following function into an anonymous function def Add (x, y    ): return X+y

Above is the function usage of the anonymous function. In addition, the anonymous function is not a wave of fame, it can really be anonymous. When working with other functional functions

 l=[3,2,100,999,213,1111,31121,333  Print   ={ " K1  : 10,"  k2   ": 100,"   K3  : 30}  print   (Max (DIC))  print  (Dic[max (Dic,key=lambda  k:dic[k]) 
res = map (lambda x:x**2,[1,5,7,4,8]) for in Res:    Print  (i) Output 2516
res = filter (lambda x:x>10,[5,8,11,9,15]) for in Res:     Print (i) Output 15

A practice of interview questions

Existing two tuples ((' A '), (' B ')), ((' C '), (' d ')), use the anonymous function in Python to generate the list [{' A ': ' C '},{' B ': ' d '}]

# Answer a Lambda  for inch zip (t1,t2)] Print (Test (T1,T2)) # Answer two Print (List (map (Lambda t:{t[0]:t[1]},zip (t1,t2 ))) # You can also write this Print  for inch zip (t1,t2)]) Coding

1. The output of the following program is: D=LambdaP:p*2T=LambdaP:p*3x= 2x=d (x) x=t (x) x=d (x)Printx2. The existing two-tuple ('a'),('b')),(('C'),('D'), use the anonymous function in Python to generate the list [{'a':'C'},{'b':'D'}]3what is the output of the following code? Please give an answer and explain. defmultipliers ():return[LambdaX:i*x forIinchRange (4)]Print([M (2) forMinchmultipliers ()]) Please modify the definition of multipliers to produce the desired result. Practice
Summary of this chapter

Say that learning built-in functions, rather than tidy up their own knowledge system. In fact, the process of organizing these built-in functions is to organize their own knowledge system.

When we lecture, we will classify: commonly used or not used, mainly or according to the scene.

A good programmer should be able to use this method at the time, the use of every built-in function is just right.

To do this, at least first understand, in order to remember when needed, and then to use it in the place.

But here, I still with a little experience of my own, to some of the usual work in the relatively more commonly used methods recommended, please be sure to focus on:

Others: Input,print,type,hash,open,import,dir

STR type code execution: eval,exec

Numbers: Bool,int,float,abs,divmod,min,max,sum,round,pow

Sequence--Lists and tuples Related: list and tuple

Sequence--string-Related: Str,bytes,repr

Sequence: Reversed,slice

Data collection--dictionaries and collections: Dict,set,frozenset

Data collection: Len,sorted,enumerate,zip,filter,map

Reference Documentation:

Https://docs.python.org/3/library/functions.html#object

Python built-in functions and anonymous 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.