Python3 built-in functions Daquan (ordered)

Source: Internet
Author: User
Tags instance method iterable pow

Built-in functions

(1) ABS (), absolute or complex modulus

1 Print (ABS ( -6)) #>>>>6

(2) All () accepts an iterator that returns true if all the elements of the iterator are true, otherwise false

1 Print (All ([1,0,3,6])) #>>>>false

(3) any () accepts an iterator that returns true if an iterator has an element true, otherwise false

1 print (Any ([0,0,0,[])) #>>>>false

(4) ASCII () invokes the __repr__ () method of the object to obtain the return value of the method.

1 Print (ASCII ([1,2,3,1,22,123])) #>>>>>[1, 2, 3, 1, 22, 123]

(5) Bin (), convert decimal into binary

1 print (BIN) #>>>>>0b1010

(6) Oct (), convert decimal to octal

1 Print (Oct (7)) #>>>>>>0o7

(7) Hex (), convert decimal to hexadecimal

1 print (hex) #>>>>>>0xf

(8) BOOL () tests whether an object is true or false.

1 print (bool ([])) #>>>>>false

(9) bytes () converts a string to a byte type

1 s= "Apple" 2 v=bytes (s,encoding= "Utf-8") 3 print (v) #>>>>>>b ' Apple '

() str () converts a character type/value type to a string type

1 s=1002 print (type (s)) #>>>><class ' int ' >3 s=str (s) 4 print (type (s)) #>>>><class ' str ' >

(one) challable () determines whether an object can be called, and the object that can be called is a Callables object, such as a function

1 Print (callable (str)) #>>>>>true

Chr () view ASCII characters corresponding to decimal numbers

Ord () to see the decimal number corresponding to an ASCII

1 Print (ASCII (12323)) #>>>>12323

Classmethod () Specifies that a method is a method of a class that is executed directly by a class, and that only one CLS parameter, when executing a method of a class, automatically assigns a value to the CLS to the class that invokes the method. There is no method for the class specified by this parameter as an instance method.

Complie () compiles a string into code that Python can recognize or can execute, or it can read the text into a string and recompile.

    compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

    将source编译为代码或者AST对象。代码对象能过通过exec语句来执行或者eval()进行求值。

Parameter source: A string or an AST (abstract syntax trees) object.

Parameter filename: The name of the code file, and some recognizable values are passed if the code is not read from the file.

   参数model:指定编译代码的种类。可以指定‘exec‘‘eval‘‘single‘

Parameter flag and Dont_inherit: These two parameters are optional.

1 s  = "print (' HelloWorld ')" 2 R = Compile (s, "<string>", "exec") 3 print (R) #>>>>>>>< Code object <module> at 0x0000000000b426f0, file ' <string> ', line 1>

(+) complex (), 创建一个值为real  + imag  *j的复数或者转化一个字符串或数为复数。如果第一个参数是字符串,则不需要指定第二个参数。

1 Print (Complex ("123")) #>>>> (123+0J)

(+) delattr () Delete the properties of the object

() dict () Create a data dictionary

1 print (Dict ()) #>>>>>>{}

Dir () returns the current range of variables, the method and the defined type list, the property of the parameter when the parameter is returned, and a list of methods with parameters.

1 Print (dir ()) #>>>>>[' __builtins__ ', ' __cached__ ', ' __doc__ ', ' __file__ ', ' __loader__ ', ' __name__ ', ' _ _package__ ', ' __spec__ ', ' R ', ' s ']

(a) Divmod () the respective vendor and remainder

1 Print (Divmod (10,3)) #>>>>> (3, 1)

(+) Enumerate () returns an object that can be enumerated, and the next () method of the object returns a tuple.

1 s = ["A", "B", "C"]2 for me, V in Enumerate (s,1): 3     print (i,v) #>>>>>1 a  2 b   3 C

(a) eval () 1. Evaluates the string str as a valid expression and returns the result of the calculation 2. Take out the contents of the string

1 s = "1 + 3 +5" 2 print (eval (s)) #>>>>>>9

EXEC () executes string or Complie method compiled string, no return value

Filter () filters, constructs a sequence equivalent to [item for item ' in Iterables if function (item)], sets the filter condition in the function, loops the elements in the iterator one by one, leaves the element with the return value true, form a filter type data.

filter(function, iterable)

参数function:返回值为TrueFalse的函数,可以为None

Parameter iterable: A sequence or an iterative object.

1 def uno (x): 2     return x > 103 v=filter (uno,[1,11,2,45,7,6,13]) 4 print (v) #>>>>><filter object At 0x0000000001143160>

Float () tells a string or integer to be converted to a floating-point number.

1 Print (float (one)) #>>>>>11.0

Format () formats the output string, format (value, Format_spec) is essentially the __format__ (Format_spec) method that called value.

1 Print ("I am {0},age{1}". Format ("Tom")) #>>>>>>i am Tom,age18

Frozenset () Creates a non-modifiable collection.

frozenset([iterable])

setfrozenset最本质的区别是前者是可变的,后者是不可变的。当集合对象会被改变时(例如删除,添加元素),只能使用set

一般来说使用fronzet的地方都可以使用set

Parameter iterable: The object can be iterated.

() GetAttr () Gets the properties of the object

getattr(object, name [, defalut])

获取对象object名为name的特性,如果object不包含名为name的特性,将会抛出AttributeError异常;如果不包含名为name的特性

And the default parameter is supplied, the default is returned.

参数object:对象

Parameter name: attribute name of the object

Parameter default: Default return value

() Globals () returns a dictionary that describes the current global variable

1 A = "Apple" 2 print (Globals ()) #>>>>>{' __name__ ': ' __main__ ', ' __package__ ': None, ' __cached__ ': none, ' a ': ' Apple ', ' __loader__ ': <_frozen_importlib_external. Sourcefileloader object at 0x00000000006a5b70>, ' __file__ ': ' d:/pycharm/pythons3/built-in function. py ', ' __spec__ ': None, ' __ Builtins__ ': <module ' builtins ' (built-in);, ' __doc__ ': None}

(+) hasattr (),hasattr(object,name)判断对象object是否包含名为name的特性(hasattr是通过调用getattr(object,name))是否抛出异常来实现的。

1 Print (Hasattr (dict, "get")) #>>>>true

(to) hash () hasheshash(object)注意:可哈希的即不可变数据类型,不可哈希即可变数据类型

如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数,在字典查找中,哈希值用于快递比价字典的键。

Two values if equal, the hash value is also equal.

(+) Help () returns the helper document for the object

Call the built-in Help system, and if it does not contain parameters, the interactive Help system will start in the console. If the argument is a string, it can be a name for the module, class, method, and so on, and the help page will be printed in the console. Parameters can also be any object

() ID () returns the memory address of the object

1 A = print (ID (a)) #>1519780304

() input () get user input

1 Print (Input ("AAA")) #>>>>>aaa

Int () Converts a string or numeric value to a normal integerint([x[,radix]])

如果参数是字符串,那么它可能包含符号和小数点。参数radix表示转换的基数(默认是10进制)。

它可以是[2,36]范围内的值,或者0。如果是0,系统将根据字符串内容来解析。

If the parameter radix is supplied, but the parameter x is not a string, the TypeError exception is thrown;

Otherwise, the parameter x must be a numeric value (a normal integer, a long integer, a floating-point number). The floating point is converted by rounding the decimal point.

If the representation range of a normal integer is exceeded, a long integer is returned.

如果没有提供参数,函数返回0

1 s = "123" 2 print (type (s)) #>>>>><class ' str ' >3 s=int (s) 4 print (type (s)) #>>>>> <class ' int ' >

Isinstance () checks whether the object is a class object, returns True or FALSE,isinstance(obj, cls)

检查obj是否是类cls的对象, 返回True或 False

1 class Foo (object): 2     pass3 obj = Foo () 4 print (Isinstance (obj, Foo)) #>>>>>true

(PNS) Issubclass () checks if a class is a subclass of another class. Returns TRUE or FALSE,,issubclass(sub, super)

检查sub类是否是super类的派生类(子类)。返回True或 False

1 class Foo (object): 2     PASS3 class Bar (foo): 4     pass5 print (Issubclass (Bar, foo)) #>>>>>> True

(+) ITER (),iter(o[, sentinel])

Returns a Iterator object. The function's resolution for the first parameter depends on the second argument.

If the second argument is not provided, the parameter o must be a collection object that supports the traversal function (__iter__ () method) or the support sequence function (__getitem__ () method).

The argument is an integer, starting from zero. If these two functions are not supported, the TYPEERROR exception will be punished.

如果提供了第二个参数,参数o必须是一个可调用对象。在这种情况下创建一个iterator对象,每次调用iterator的next()方法来无

The call to the parameter O, if the return value equals the parameter Sentinel, triggers the stopiteration exception, otherwise the value is returned.

() Len () returns the length of the object, which can be a sequence type (string, tuple, or list) or a mapping type (such as a dictionary)

1 s = "AJLJFLAJFL" 2 print (len (s)) #>>>>>10

() List constructor.

Locals () print a dictionary of the currently available local variables

Map (),map(function, iterable,...)

For each element in the parameter iterable, the Fuction function is applied and the result is returned as a list.

If there are multiple iterable parameters, then the Fuction function must receive multiple arguments, and the elements at the same index in those iterable will be parallel as arguments to the function functions.

如果一个iterable中元素的个数比其他少,那么将用None来扩展改iterable使元素个数一致。

如果有多个iterable且function为Nonemap()将返回由元组组成的列表,每个元组包含所有iterable中对应索引处值。

1 Li = [1,2,3]2 data = map (lambda x:x*100,li) 3 print (type (data)) #>>>>>><class ' map ' >4 data = List (data) 5 print (data) #>>>>>>>[100, 200, 300]

Max () returns the maximum value in the given element,max(iterable [,args...][, key])

If you supply only the iterable parameter, the function returns the largest non-empty element that can traverse an object, such as a string, tuple, or list.

If more than one argument is supplied, the one with the largest value is returned.

The optional parameter key is a single-parameter sort function.

如果提供key参数,必须是以命名的形式,如:max(a, b, c, key =fun)

(Meoryview) ()

MIN () returns the minimum value in the given element,min(iterable [,args...][, key]),具体用法跟max()相同

Next () returns an iterator to the next item in the data structure (such as a list)

() object (),获取一个新的,无特性(geatureless)对象。Object是所有类的基类。它提供的方法将在所有的类型实例中共享。

Open () Opens fileopen(filename [, mode [, bufsize]])

打开一个文件,返回一个file对象。 如果文件无法打开,将处罚IOError异常。

应该使用open()来代替直接使用file类型的构造函数打开文件。

The parameter filename indicates the path string of the file that will be opened;

参数mode表示打开的模式,最常用的模式有:‘r‘表示读文本,‘w‘表示写文本文件,‘a‘表示在文件中追加。

Mode的默认值是‘r‘

当操作的是二进制文件时,只要在模式值上添加‘b‘。这样提高了程序的可移植性。

可选参数bufsize定义了文件缓冲区的大小。0表示不缓冲;1表示行缓冲;任何其他正数表示使用该大小的缓冲区;

A negative number means that the system default buffer size is used, which is often a row buffer for TTY devices, and is often completely buffered for other files. If the parameter value is omitted.

Use system default values.

(a) The POW (x, y, z) power function, which means to take the Y power of X., if there is a third parameter z, it means that the result of the exponentiation takes the remainder of the third parameter

1 S=pow (2,8,) 2 print (s) #>>>>2563 S2=pow (2,8,5) 4 print (s2) #>>>>>1

() print () output function

(Wuyi) Property ()

Range () generates a specified range of numbers as needed to provide the control you need to iterate over the specified number of times

用于创建包含连续算术值的列表(list)。常用于for循环。参数必须是普通整数。

参数step默认值为1,参数start的默认值为0

Full parameter call this function will return a list of ordinary integers.

step 可以是正整数或者负整数。不可以为0,否则将触发ValueError异常。

(repr) Converts any value to a string, in the form of a timer readrepr(object)

Returns a string representation of an object. You can sometimes use this function to access operations.

对于许多类型来说,repr()尝试返回一个字符串,eval()方法可以使用该字符串产生对象;

Otherwise, a string containing the class name and other two outer information is returned, enclosed in angle brackets.

Reversed () reverse, Reverse object

(round) rounding up ()round(x [, n])

对参数x的第n+1位小数进行四舍五入,返回一个小数位数为n的浮点数。

参数n的默认值是0。结果是一个浮点数。如round(0.5)结果为1.0

() set () to convert the object to a collection

SetAttr () corresponds to GetAttr ()

(slice) Slicing function

1 s = ["A", "B" "C", "D"]2 print (Slice (1,3,s))

(sorted) Sort by ()

List sort, row by axis

Higher order functions, sorted by absolute size

String sorting, sorted by ASCII size

If you need to sort a tuple, you need to use the parameter key, which is the keyword.

Reverse sort, reserve=true

SUM () summation

(million) tuple () tuples constructor

() type () displays the type to which the object belongs

() Zip () to pair the objects individually

Python3 built-in functions Daquan (ordered)

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.