1. Python pow() 函数
pow(x, y[, z])
函数是计算 x 的 y 次方,如果 z 在存在,则再对结果进行取模,其结果等效于 pow(x,y) %z
2.Python int() 函数
class int(x, base=10)
x – 字符串或数字。
base – 进制数,默认十进制。
3.python round()函数
round(a,b)
第一个参数是一个浮点数,第二个参数是保留的小数位数,可选,如果不写的话默认保留到整数
在python2.7的doc中,round()的最后写着,“Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0.” 保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。所以round(0.5)会近似到1,而round(-0.5)会近似到-1。
但是到了python3.5的doc中,文档变成了"values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice." 如果距离两边一样远,会保留到偶数的一边。比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。
4.Python eval() 函数
eval(expression[, globals[, locals]])
expression – 表达式。
globals – 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
>>>x = 7
>>> eval( '3 * x' )
21
>>> eval('pow(2,2)')
4
>>> eval('2 + 2')
4
>>> n=81
>>> eval("n + 4")
85
5.nonlocal
Python3引入了nonlocal声明。它的作用是把变量标记为自由变量,即使在函数中为变量赋予新值了,也会变成自由变量。如果为nonlocal声明的变量赋予新值,闭包中保存的绑定会更新。
def excepter(f):
i = 0
t1 = time.time()
def wrapper():
try:
f()
except Exception as e:
nonlocal i
i += 1
print(f'{e.args[0]}: {i}')
t2 = time.time()
if i == n:
print(f'spending time:{round(t2-t1,2)}')
return wrapper
关键词**nonlocal**,声明i非局部变量,而是自由变量,如果不声明,i+=1则表示i是函数wrapper内部的局部变量。
6.slice对象
仔细对比发现还是第一种方法好。感觉
a = [1,3,5,7,9,0,3,5,7]
a_ = a[5:1:-1]
#从第5个开始逆切片,到1截止不包括位置1的数字。
named_slice = slice(5,1,-1)
a_slice = a[named_slice]
a_
Out: [0, 9, 7, 5]
a_slice
Out: [0, 9, 7, 5]
class slice(start, stop[, step])
返回一个表示由 range(start, stop, step) 所指定索引集的 slice对象,它让代码可读性、可维护性变好。
7.python zip()函数
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c)) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>
tuple() 将对象转为一个不可变的序列类型 转元祖
8.集合
9.检查对象:callable,ascii
检查对象是否可被调用
In [1]: callable(str)
#str表示“对象”
Out[1]: True