Quick Python syntax: 1. Data type built-in functions

 

 (1) built-in data types used

classification type name description
digital int Integer
float Float
complex plural
bool Boolean value
sequence str String (immutable sequence)
list List
tuple Tuples (immutable sequence)
range Integer (immutable sequence)
bytes Byte array (immutable sequence)
bytearray Variable byte array
Mapping dict dictionary
set set Variable collection
frozenset Immutable collection
None NoneType Empty object, it does not have any properties

 

 

  (2) checking the type commonly used methods

usage Types of description For example
id ( Examples ) Built-in functions Returns an object's identity (integer)

id(a)

type ( example ) Built-in functions It returns an object instance of type type(a)
is Operators Compares two objects of the same status

a is b

type(a) is str

of the type (A) IS of the type (b)   # A and b whether the same type

the isinstance ( instance, class name ) Built-in functions Whether the reference object is an instance of the class parameters

isinstance (S, List) # S whether the list

the isinstance (F, Foo)   # F is an instance of class Foo

 

 

  (3) built-in functions common

name Brief usage By way of example or illustration.
computation
abs() Returns a positive number abs(x) abs(a)
pow() x y power calculation, and the result of the modulo z pow(x, y[,z])

POW (2,3,3) # 2 results

round() The x in negative rounding taken n times 10 round(x[, n=0]) Rounding rules detailed below
divmod() Will be a divided by b quotient and the remainder is returned as a tuple divmod(a, b)

divmod (10,3) # results (3,1)

Examples of built-in data types generated
int() The word or word string into the parameter, generating an integer examples int(x[, base=10]) The default is 10 base, see the following example
float() The word or word string into the parameter, generating a floating point examples float(x)

a float (. 3) # 3.0 Results

complex() Generating a plurality Examples complex(r[, i]) Less frequently used
bool() Generate a Boolean value example bool([x]) The default return False without reference into the
list() Generate a list of examples list([item]) item shall be iterables
dict() Examples generation dictionary dict([m]) See below
tuple() Generator set of examples tuple([items]) item shall be iterables
str() Generated strings Examples str([object]) A method of object reference into __str__
range() Examples range created

range(stop)

range(start, stop [,step])

range对象可以用迭代、也可用切片访问
set() 生成集合实例 set([items]) item须是可迭代对象
frozenset() 生成不可变集合实例 frozenset([items]) item须是可迭代对象
slice() 生成切片对象

slice(stop)

slice(start, stop [,step])

较少直接使用

bytes() 生成不可变字节数组实例 bytes([source [,encoding [,errors]]]) 详见下述
bytearray() 生成可变字节数组实例 bytearray([source [,encoding [,errors]]]) 用法同上,内容可变
memoryview() 生成memoryview实例 memoryview(obj) 较少用到
object() 生成一个基类实例 object() 较少用到
编码与解码
hex() 将数值x用16进制字符串表示 hex(x)

hex(16) # 结果为'0x10'

oct() 将数值x用8进制字符串表示 oct(x)

oct(16) # 结果为'0o20'

bin() 将数值x用2进制字符串表示 bin(x)

bin(8) # 结果为'0b1000'

ord() 将单字符转换成utf-8数值 ord(c)

ord('a') # 结果为97

ord('数') # 结果为25968

chr() 将数值x转换成单字符字符串 chr(x)

chr(97) # 结果为'a'

chr(25968) # 结果为'数'

ascii() 像repr()那样显示对象,非ASCII字符显示为转义序列 ascii(object) 较少用到
序列操作
len() 返回s中包含的项数 len(s) s可以是:列表、元组、字符串、集合、字典
min() 如果只有1个参数s,返回s中各项的最小值。如果有多个参数,返回各个参数中的最小值。 min(s[, args, ...])

s可以是可迭代对象

min([1,3,5]) # 结果为1

min(1,3,5,7) # 结果为1

max() 如果只有1个参数s,返回s中各项的最大值。如果有多个参数,返回各个参数中的最大值。 max(s[, args, ...])

s可以是可迭代对象

min([1,3,5]) # 结果为5

min(1,3,5,7) # 结果为7

sum() 计算可迭代对象iter中所有项的和,initial为累加初始值,默认为0。只能用于数值计算。 sum(iter[ ,initial])

sum([1,2,3]) # 结果为6

sum([1,2,3], 10) # 结果为16

迭代操作
all() 若可迭代对象iterable中的所有值都为True,则返回True。 all(iter)

all([0,1,2,3]) # 结果为False

any() 若可迭代对象iterable中的任意值为True,则返回True。 any(iter)

any([0,1,2,3]) # 结果为True

enumerate() 根据入参迭代器,产生一个新迭代器,其中每个元素为一个元组:内含一个计数值和原迭代出的值。 enumerate(iter[ ,start=0])

for i,x in enumerate(['a','b'])

    pass

    # 结果迭代出(0,'a'), (1,'b')

zip() 产生一个新迭代器,第n个元素为一个(s1[n], s2[n], ...)的元组,其长度为最短的一个迭代器长度。 zip([s1 [, s2 [, ...]]])

a = [1,2,3]

b = ['x','y']

for t in zip(a, b)

    pass

    # 迭代结果为(1,'x'), (2,'y')

sorted() 根据入参迭代器的内容排序,创建有序列表 sorted(iter, *, key=None, reverse=False) 详见下述
reversed() 产生一个迭代器,将入参序列的所有元素位置颠倒(注意:跟sorted()完全不同) reversed(seq)

for x in reversed([1,2,'a']):

    pass

    # 迭代结果为 'a', 2, 1

filter() 产生一个迭代器,其内容是对入参iter中的每个元素使用func函数进行过滤,只有func返回True的才被加入新迭代器。 filter(func, iter)

a = [1,2,3,4,5,6,7,8]

filter(lambda x:x%2==1, a)

# 迭代器中内容为 1,3,5,7

map() 产生一个迭代器,其每一项是将函数func应用到iter中的每一项返回的结果。若入参有多个iter迭代器,则相应的函数func应有多个入参。 map(func, iter, ...)

map(lambda x:x*2, [1,3,5,7])

# 迭代器中内容为 2,6,10,14

iter() 返回一个可生成object中各项的迭代器。 iter(object[ ,sentinel])

较少直接使用

next() 返回迭代器iter中的下一项。 next(iter[ ,default])

较少直接使用

对象实例操作
id() 返回object的唯一整数标识符(这是一个内存位置)。 id(object)

结果为一个整数,较少直接使用

type() 当单参数调用时,返回入参object的类型。当三参数调用时,创建一个新type对象(一般用于元类)。

type(object)

type(name, bases, dict)

type(1) # 结果为<class 'int'>

type('a') # 结果为<class 'str'>

isinstance() 如果object是clsinfo类的一个实例,则返回True。clsinfo可以是一个含多个类的元组。 isinstance(object, clsinfo)

# 设有一个名为Foo的自定义类

f = Foo()

isinstance(f, Foo) # True

isinstance(f, (Foo,list)) # True

isinstance([1,2], (Foo,list)) # True

isinstance(f, (list,tuple) # False

repr() 返回object的字符串表示形式。 repr(object) 一般在类内部的__repr__()方法会定义本对象的字符串表示形式。
dir() 返回object对象的属性名(含方法名)列表,若object是一个模块,则返回其内部定义的符号列表。 dir(object) 如果类内部定义了__dir__属性,则返回此值。
hasattr() 若name是object的属性名,则返回True hasattr(object, name)

入参name是一个字符串

getattr() 返回对象的name属性的值,若无此属性,则default是可选的返回值,否则引起AttributeError。 getattr(object, name [,default])

a = getattr(obj, 'p1')

# 效果同 a = obj.p1

setattr() 设置对象的属性 setattr(object, name, value)

setattr(obj, 'p1', a)

# 效果同 obj.p1 = a

delattr() 删除对象的属性 delattr(object, name)

del(obj, 'p1')

# 效果同 del obj.p1

hash() 返回对象的整数散列值。一般可变对象不会定义散列值,除非类内部定义了__hash__()方法。 hash()

hash('abc') # 结果为526986374

hash(3.14)  # 结果为1846836513

callable() 检查一个对象是否是可调用的。但有时即便返回 True,object 仍然可能调用失败。 callable(object) 对于函数、方法、lamdba表达式、类、实现了__call__()方法的类实例,它都返回True。
类操作
staticmethod() 创建在类中使用的静态方法。 staticmethod(func) 一般通过@staticmethod装饰器隐式调用该函数
classmethod() 创建在类方法。 classmethod(func) 一般通过@classmethod装饰器隐式调用该函数
issubclass() 如果class是clsinfo的子类,或class是基于抽象基类clsinfo注册的,则返回True。clsinfo可以是一个含多个类的元组。 issubclass(class, clsinfo)

issubclass(Foo, BaseFoo) # 结果为 True

issubclass(Foo, (BaseFoo,list) # 结果为 True

super()

返回一个代理对象,提供可以调用基类中的方法的手段。type是当前子类名,object一般是self。

在Python3中,在子类方法中可以省略type和object参数,直接简写成:super()

super(type [,object])

class B(A):

  def foo(self):

    # 调用基类A的foo方法

    super(B,self).foo()

    # 在Python3中可简写成:

    # super().foo()

property() 创建一个虚拟属性。fget, fset, fdel分别为自定义的属性读取、设置、删除方法,doc为文档字符串。 property(fget=None, fset=None, fdel=None, doc=None)

class C:

  def __init__(self):

    self._x = 'c'

  def gx(self):

    return self._x

  x=property(fget=gx, doc='a')

  # 定义了一个只读的属性x

域操作
globals() 返回代表当前全局作用域的所有符号的字典。 globals()

globals()

locals() 返回代表当前局部作用域的所有符号的字典。 locals()

locals()

var() 返回object的所有属性和属性值的字典对象,如果没有入参,则相当于调用locals() var([object])

vars(obj)

输入输出与文件操作
input() 显示prompt提示信息,并读取一行输入,将读入内容不作任何修改作为字符串返回。(Python3中取消了原raw_input()函数) input([prompt])

>>> input('pls ipt:')

pls ipt:123

# 返回结果为:'123'

print() 打印一系列值到屏幕上。入参中可设置:多个显示对象之间的分隔符、换行符、输出设备、强制刷新等,一般不用修改。 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

一般用于调试用

open() 打开文件并返回一个新文件对象。 open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

在文件操作章节详细描述

杂项
eval() 计算入参表达式expr的值,expr是一个字符串或代码对象。globals和locals参数可指定操作时的全局和局部命名空间映射对象。 eval(expr, globals=None, locals=None)

x = 1

eval('x+1') # 结果为2

exec() 执行Python语句,入参code可以是字符串、文件或代码对象。globals和locals参数可指定操作时的全局和局部命名空间映射对象。 exec(code[, globals[, locals]])

x = 1

code = """s = x + 1

print(s)"""

exec(code) # 结果为2

exec(code, {'x':10}) # 结果为11

format() In accordance with the format value format_spec convert formatted string, the operation invocation value .__ format __ () method. format(value[, format_spec])

Usually in the format string called implicitly

help() Call the built-in help system. object can be a string (a block name, class names, function names, method names, keywords, document theme name), if other types of objects, help screens associated with that object appears. help([object])

help('math')

compile() The source code is compiled into an object the object, the result may be used to eval () and exec () function. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

If not, then development framework, usually with less than

breakpoint() Python3.7 in new built-in functions, is used to set the breakpoint program is running, the program automatically enters the debugger to run that function. This is a convenient function that lets you easily enter Pdb Debugger (not to explicitly import debugging module, etc.). breakpoint(*args, **kws) The need to set a breakpoint in place direct calls breakpoint () can

 

 

 

● round(x[, n])

Description:

In Python3, when numbers are rounded to 5 and is 1 bit decimal, the rounding rules are as follows: a number if they are rounded before the number is even, then the rounding direction towards zero; otherwise away from zero, positive and negative numbers follow this rule. Rounding other bits do not apply this rule, still in accordance with the ordinary mathematical rules.

For example:

>>> round(2.5)  # 结果为2
>>> round(-2.5) # 结果为2
>>> round(3.5)  # 结果为4
>>> round(-3.5) # 结果为4

返回索引

 

 

 

● int(x[, base])

说明:

x可以是数字或字符串,base是入参的转换进制基数,可以是2、8、16、16等,转换结果总是10进制整数。

举例:

>>>  int('100') # 结果为100
>>>  int('100', 10) # 结果为100
>>>  int('100', 16) # 结果为256
>>>  int('100', 2) # 结果为4

返回索引

 

 

 

● dict([m])

说明:

入参m若是字典,则dict(m)就创建一个m浅复制。若m不是字典,则必须能够产生(key, value)形式的迭代值。也可用关键字创建字典,见下例。

举例:

>>>  dict('a'=1, 'b'=2) # 结果为{'a':1, 'b':2}
>>>  dict() # 结果为空字典{}

返回索引

 

 

 

● bytes([source [,encoding [,errors]]])

说明:

生成不变字节数组,入参source为原始输入字符串,入参encoding指定要使用的字符编码方式。

举例:

>>> x = bytes()   # 结果为空字节数组 b''
>>> x = b''   # 结果同上
>>> x = bytes('abc')   # 结果为 b'abc'
>>> x = bytes('ab数字', 'utf-8')  # 结果为 b'ab\xe6\x95\xb0\xe5\xad\x97' 

返回索引

 

 

 

● sorted(iter, *, key=None, reverse=False)

说明:

根据iter迭代器中的各项值的内容进行排序(从小到大),创建有序列表,一般只能对数字或字符串进行排序。key是个单参数函数,可以对元素在被排序前进行预处理,将一些常规来说不能排序的元素预处理成可排序的数字或字符串。reverse是个标志位,用以指出是否逆序(从大到小)排序。(注意:Python3最新版本中已废除了cmp参数)

举例:

>>>  sorted([1,7,3,5])  # 结果为[1,3,5,7]
>>>  sorted([1,7,3,5], reverse=True)  # 结果为[7,5,3,1]
>>>  sorted(['c','b','a']) # 结果为['a','b','c']
>>>  sorted([('b',2),('a',1)], key=lambda x:x[1]) # 结果为[('a',1),('b',2)]
>>>  # 上例说明:入参列表中的元素为元组,一般不能排序。但这里用lambda生成了一个匿名函数,对元素进行预处理,取出每个元素元组中的数字,然后用这个数字作为排序依据,给sorted()函数进行排序

返回索引

 

 

 

 

 

 

返回标题

 

Guess you like

Origin www.cnblogs.com/initcircuit/p/11488026.html