|
python19 内置函数
- all函数
print (all([0,-5,3]))
#非0就为真
print (all([1,-5,3]))
- any函数
print (any([0,-5,3]))
#只要非空,就为真
a = ascii([1,2,'一二三'])
print (type(a),[a])
可以看到两边用双引号被括起来了,这个函数的作用就是让其内存中的数据变成可打印的字符串格式。
这个函数实际用处不大。
- bin函数
将十进制数字转为二进制数字
- bool
判断真假
- bytearray函数
a = bytearray('abcde',encoding='utf-8')
print (a)
默认字符串是不可修改的,不过这里可以通过字节个事的ASCII码来修改。
print (a[0])
print (a[1])
103对应的g
这个bytearray功能很少用。
- bytes函数
a = bytes('abcde',encoding='utf-8')
print (a.capitalize(),a)
变为字节格式
- callable函数
print (callable([])) #判断列表是否可调用
def abc ():
pass
print (callable(abc)) #判断函数是否可调用
判断是否是可调用的(只有带小括号的才可以被调用)
- chr函数
返回ASCII码对应表内容
- ord函数
ord和chr是反过来的,通过字符查看对应的ASCII表数字
- compile、exec、eval函数
compile用来将字符串转为可执行的代码
code = 'for i in range(10):print(i)'
print (compile(code,'','exec'))
打印内存中字节码对象
exec(code)
code = 'print (10)' eval(code)
如果使用eval的话,可以直接将其转换并执行,不需要像compile先编译
这个好处是可以调取txt文档中的字符串来执行,类似import 导入模块,但是import 只能在本地导入,但是该函数可以从远程调取字符串来执行。
code = 'print (10)' exec (code)
其实直接使用exec就可以执行字符的代码了
eval:可以执行非语句的字符串
exec可以执行带语句的字符串比如for循环
- divmod函数
divmod用来取除法的商和余数
- filter函数 (lambda n:print (n)) (10) #lambda是匿名函数
匿名函数用来处理简单的条件或运算等简单的功能,一般匿名函数很少单独使用。
calc = lambda n:3 if n<4 else n print (calc(5))
lambda配合filter来使用:
res = filter(lambda n:n>5,range(10)) #过滤大于n的数(n根据range(10)生成0到9的数字)
print (res)
print (dir(res))
可以看到当前res是迭代器,所以需要通过for来循环
for i in res: print (i)
res = map(lambda n:n*2,range(10)) for i in res:
print (i)
map对传入的值进行处理,处理的方式就是匿名函数中的n*2,然后进行print
上面的代码,与下面的推到式列表结果一样
res = [i*2 for i in range(10)] for i in res:
print (i)
如果没有map的话print的就是迭代器
import functools res = functools.reduce(lambda x,y:x+y,range(10))
#reduce在2.X中属于内置函数,不过在3.X中就是标准库函数了,需要import
print (res)
将运算的最后结果打印出来。
- frozenset函数
可变集合可以看到remove、update等方法,可以用来改变集合
不可变集合中就看不到可以改变该集合的方法
- globals函数
a = 1
b = 2
c = 3
print (globals())
globals可以将当前文档所有内容进行判断,但凡是变量格式(a = 1),都会讲这个=符号变为:,以字典的格式打印。
可以用来判断当前文档中是否有该变量(只是在全局作用域判断)
- locals函数
def test (): abc = 123
print (locals()) #判断局部作用域是否有变量,并以字典的格式打印出来
test()
- hex函数
将十进制转为十六进制
- max、min函数
a = [1,5,3,2,6]
print (max(a))
print (min(a))
- oct函数
将十进制转为八进制
- pow函数
求的是2的4次方
- repr函数
repr可以用字符串来表示指定的数据
- round函数
print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))
返回浮点数x的四舍五入值。
a = {6:2,8:0,1:4,-5:6,99:11,4:22}
print (a)
b = sorted(a.items()) #sorted只对key排序,加上.items()就会对整个字典排序,以列表打印出来
print (b)
c = sorted(a.items(),key=lambda x:x[1]) #根据value的值进行排序 print (c)
- sum函数
sum((2, 3, 4), 1) # 元组计算总和后再加 1
sum([0,1,2,3,4], 2) # 列表计算总和后再加 2
- zip函数
a = [1,2,3]
b = [4,5,6]
c = [7,8,9,10,11]
zipped = zip(a,b) # 打包为元组的列表
for i in zipped:
print (i)
结果是两个列表一 一对应,以元组的形式显示
for m in zip(a,c): print (m)
元素个数与最短的列表一致
d = zip(*zipped)
for x in d:
print (x)
与 zip 相反,可理解为解压,返回二维矩阵式
- import函数
__import__('time') #可以通过该函数import字符串来去import某个模块
a = 'time'
__import__(a)
|
|