python--built-in functions and anonymous functions

Source: Internet
Author: User
Tags abs chr ord pow

Built-in functions

Next, let's take a look at the built-in functions in Python. As of Python version 3.6.2, Python now provides us with 68 built-in functions altogether. They are all the functions that Python gives you to use directly. Some of these functions we have used, some of which we have not, and some are sealed, must wait for us to learn new knowledge to unlock the seal. Well, let's meet today. Python's built-in functions. So many functions, where should we learn from?

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 ()

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

Input/output Related:

Input () inputs

s = input ("Please enter content:")  #输入的内容赋值给s变量print (s)  #输入什么打印什么. Data type is str
s = input ("Please enter content:")  #输入的内容赋值给s变量print (s)  #输入什么打印什么. Data type is str

Print () output

def print (self, *args, sep= ", end= ' \ n ', File=none): # Known special case of print    " ""    print (value, ..., sep= ", End= ' \ n ', File=sys.stdout, flush=false)    file:  default is output to screen, if set to file handle, output to file    Sep:   Print separators between multiple values, default to Spaces    end: At   the end of each print, the default is a newline character    flush: outputs the content to a stream file immediately, without caching    ""
def print (self, *args, sep= ", end= ' \ n ', File=none): # Known special case of print    " ""    print (value, ..., sep= ') ', end= ' \ n ', File=sys.stdout, flush=false)    file:  default is output to screen, if set to file handle, output to file    Sep:   Print delimiters between multiple values, The default is a space end    :   each time the end of the print, the default is a newline character    flush: The content is immediately output to a stream file, not cached    "" "
f = open (' Tmp_file ', ' W ') print (123,456,sep= ', ', file = f,flush=true)
f = open (' Tmp_file ', ' W ') print (123,456,sep= ', ', file = f,flush=true)
Import Timeimport sysfor i in Range (0,101,2):     time.sleep (0.1)     char_num = I//2      #打印多少个 #     per_str = '%s%%:% s\n '% (i, ' * ' * char_num) if i = = "\r%s%%":%s '% (i, ' * ' *char_num)     print (per_str,end= ", File=sys.stdout, Flus H=true)
Import Timeimport sysfor i in Range (0,101,2):     time.sleep (0.1)     char_num = I//2      #打印多少个 #     per_str = '%s%%:% s\n '% (i, ' * ' * char_num) if i = = "\r%s%%":%s '% (i, ' * ' *char_num)     print (per_str,end= ", file=sys.stdout, flu Sh=true)

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 = (all in a) L = [1,2,3]print (hash (t))  #可hashprint (hash (l))  #会报错 "Result: typeerror:unhashable type: ' List '
T = (all in a) L = [1,2,3]print (hash (t))  #可hashprint (hash (l))  #会报错 "Result: typeerror:unhashable type: ' List '

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 time

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 ():p Assprint (Callable (func))  #参数是函数名, callable, returns Trueprint (callable (123))   #参数是数字, not callable, returns false

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))  #查看列表的内置方法print (dir (int))  #查看整数的内置方法
Print (dir (list))  #查看列表的内置方法print (dir (int))  #查看整数的内置方法

Execution of the STR type code

Http://www.cnblogs.com/Eva-J/articles/7266087.html

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,bytesarry,memoryview,ord,chr,ascii,repr

Sequence: Reversed,slice

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

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

Filter and map:http://www.cnblogs.com/eva-j/articles/7266192.html

Sorted Method: Http://www.cnblogs.com/Eva-J/articles/7265992.html

anonymous functions

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

#这段代码def Calc (n):    return N**nprint (calc) #换成匿名函数calc = Lambda n:n**nprint (Calc (10))

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

function name = Lambda parameter: Return value # parameter can have multiple, separated by commas # anonymous function no matter how complex the logic, can only write a line, and the end of the logical execution of the content is the return value # return value and normal function can be any data type

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 (Max (l)) dic={' K1 ': Ten, ' K2 ': +, ' 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 I in Res:    print (i) Output 125491664
res = filter (lambda x:x>10,[5,8,11,9,15]) for I in Res:    print (i) Output 1115

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 '}]

#答案一test = Lambda T1,t2: [{i:j} for I,j in Zip (t1,t2)]print (Test (T1,T2)) #答案二print (list (map (lambda t:{t[0]:t[1]},zip (T1, T2))) #还可以这样写print ([{i:j} for I,j in Zip (t1,t2)]))
#答案一test = Lambda T1,t2: [{i:j} for I,j in Zip (t1,t2)]print (Test (T1,T2)) #答案二print (list (map (lambda t:{t[0]:t[1]},zip (T1, T2))) #还可以这样写print ([{i:j} for I,j in Zip (t1,t2)]))

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.