python 各种函数作用记录(持续更新)
input() #输入函数,提供用户输入值
例如:name = input()
print(name)
ord() #函数获取字符的整数表示
例如:>>> ord('A')
65
>>> ord('中')
20013
chr() #函数把编码转换为对应的字符
例如:>>> chr(66)
'B'
>>> chr(25991)
'文'
encode() #可以编码为指定的bytes
例如:>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('ascii')
Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
纯英文的str可以用ASCII编码为bytes,内容是一样的,含有中文的str可以用UTF-8编码为bytes。含有中文的str无法用ASCII编码,因为中文编码的范围超过了ASCII编码的范围,Python会报错。
decode() #将已知的字节流要把bytes变为str
例如:>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'
append() #末尾增加一个值
例如:>>>a = ["liyuan","xieming",3]
>>>a.append("yuanlu")
>>>a
['liyuan', 'xieming', 3, 'yuanlu']
insert() #指定地方插入一个值
例如:>>>a = ["liyuan","xieming",3]
>>>a.insert(1,"yuanlu")
['liyuan', 'yuanlu', 'xieming', 3]
pop() #删除某个值,括号内不填表示删除末尾
例如:>>>a = ["liyuan","xieming",3]
>>>a.pop(1)
xieming
>>>a
['liyuan', 3]
range() #可以生成一个整数序列
例如:>>>a = list(range(5))
>>>a
[0, 1, 2, 3, 4]
yield # 在函数中存在yield关键字就是generator的函数
generator 函数执行过程中遇到yield关键字就会返回,再次执行时从上次返回的yield语句处继续执行。
map #map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
例如:def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce # reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
例如:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
filter # filter()设定一个判断结果,filter将结果为Ture的输出,False的过滤
例如:def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
stored # stored()对结果进行排序,stored可以接收参数来修改排序规则
例如:sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

浙公网安备 33010602011771号