内建函数

abs() :返回绝对值
sum():求和
divmod():返回商和余数
pow():幂
complex():复数
>>> abs(-10)
10
>>> sum([1,2,3,4])
10
>>> divmod(5,2)
(2, 1)
>>> pow(3,2)
9
>>> complex('1+2j')
(1+2j)
int():把字符串或则数字转换为整形
float():把字符串或则数字转换为浮点型
>>> int("1.45")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.45'
>>> int("145")
145
>>> int(1.45)
1
>>> float("1.5")
1.5
>>> float("123a")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '123a'
>>> float(1)
1.0
round() 截取浮点数
>>> round(1.3456,2) 1.35
max(),min():返回最大值和最小值
>>> max(1,2,0.5,3,4) 4 >>> min(1,2,0.5,3,4) 0.5
all函数:可迭代对象中所有元素为真(或则可迭代对象为空),返回True,有元素为假,返回False
any函数:可迭代对象中有元素为真,就返回True,都为假(或则可迭代对象为空),返回False
>>> all([]) True >>> all([0,1,2]) False >>> all([1,1,2]) True >>> any([]) False >>> any([0,1,2]) True >>> any([0,0]) False >>> any([1,2,3]) True
ascii函数:把一个对象变成字符串形式显示,用的比较少
str函数与ascii函数也是相同功能,两者区别见代码
>>> str('a')
'a'
>>> ascii('a')
"'a'"
bin():十进制转换为二进制
hex(): 十进制转换为十六进制
oct():十进制转换为八进制
>>> bin(20) '0b10100' >>> hex(20) '0x14' >>> oct(20) '0o24'
bool():判断对象是否为真
>>> bool(0) False >>> bool([]) False >>> bool([1]) True
bytes():返回一个byte对象
bytearray():,可以修改二进制,返回一个byte数组
两者区别:对bytes操作就相当于对字符串操作,无法修改值,对bytearray相当于对列表操作,可以直接修改元素的值
>>> a = bytes("abc",encoding='utf-8')
>>> b = bytearray("abc",encoding='utf-8')
>>> a
b'abc'
>>> b
bytearray(b'abc')
>>> a[0] = 51
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object does not support item assignment
>>> b[0] = 51
>>> b
bytearray(b'3bc')
>>> a
b'abc'
callable() :判断是否可被调用(如函数,类均可被调用)
chr():数字对应ASCII字符
ord():ASCII字符对应数字
>>> chr(97)
'a'
>>> ord('a')
97
dict():创建一个字典
list():创建列表
set():创建集合
>>> dict(zip(('a','b'),(10,20)))
{'a': 10, 'b': 20}
>>> dict((('a','b'),(10,20)))
{'a': 'b', 10: 20}
>>> dict()
{}
>>> list()
[]
>>> list((i for i in range(5)))
[0, 1, 2, 3, 4]
>>> set()
set()
>>> set([1,3,5,5,7])
{1, 3, 5, 7}
dir(object):查询对象下有什么方法
>>> dir(dict) ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop',
'popitem', 'setdefault', 'update', 'values']
enumerate(iterable, start=0):取得可迭代对对象的下标,下标可以指定开始数字,返回一个迭代器
>>> seasons = ['spring','summer','fall','winter'] >>> list(enumerate(seasons)) [(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
eval():将字符串str当成有效的表达式来求值并返回计算结果
exec():用来执行储存在字符串或文件中的python语句
lambda :匿名函数,与其他函数结合使用比较多,一般不单独使用。
filter(function, iterable):过滤出合格的结果
>>> a = filter(lambda n:n>5,range(10)) >>> list(a) [6, 7, 8, 9]
用列表生成式表示(n for n in range(10) if n>5)
map(func,*iterables):对可迭代对象以func的函数功能进行处理,
>>> b = map(lambda x:x*2,range(5)) >>> list(b) [0, 2, 4, 6, 8]
用列表生成式表示f(n*2 for n in range(5))
reduce():
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> from functools import reduce >>> reduce(lambda x,y:x*y,range(1,5)) 24
frozenset():变为不可变的集合
globals():整个程序全局的变量名,字典形式。
locals():整个程序局部的变量名,字典形式。
id():返回内存地址
type() :查看数据类型
zip():把可迭代对象一一对应
zip()函数创建的是一个只能访问一次的迭代器
>>> a = zip([1,2,3],['a','b','c'])
>>> dict(a)
{1: 'a', 2: 'b', 3: 'c'}
>>> dict(a)
{}
sorted():排序
>>> sorted([1,2,5,3,4])
[1, 2, 3, 4, 5]
>>> a = {6:2,8:0,1:4,-5:6}
>>> sorted(a) #按键排序
[-5, 1, 6, 8]
>>> sorted(a.items(),key=lambda x:x[1]) #按值排序
[(8, 0), (6, 2), (1, 4), (-5, 6)]
>>> sorted(zip(a.values(),a.keys())) #按值排序
[(0, 8), (2, 6), (4, 1), (6, -5)]
slice:创建一个切片对象,可以被用在任何切片允许使用的地方
items = [0,1,2,3,4,5,6]
a = slice(1,4) #尽量用有意义的变量命名,增加程序可读性
print(items[a]) ->[1, 2, 3]
可以直接切片,为什么要用slice呢?
因为代码中如果出现大量的硬编码下标值会使得程序可读性和可维护性大大降低。
__import__ 只知道字符串,用这种方式import。
如:__import__ 'abcd'
delattr:类 getattr()issubclass()object()setattr() classmethod() 持续更新
详细内容详见:
https://docs.python.org/3/library/functions.html?highlight=built#func-dict

浙公网安备 33010602011771号