python3中内置函数介绍
在python3 中,filter、map、reduce已经不是内置函数,即,python3中三者是class,返回结果变成了可迭代的对象
1.filter(function,iterable)
通过function过滤条件,去获取iterable中你想要的数据。
from collections import Iteratortest_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]f = filter(lambda x: x % 3 == 0, test_list)# filter 得到的是一个迭代器print(isinstance(f, Iterator))f.__next__()for i in f: print(i)#输出True69
立即学习“Python免费学习笔记(深入)”;
2.map(function, iterable)
接受一个函数和可迭代对象(如列表等),将函数依次作用于序列的每一个元素,形成一个新的迭代器。
from collections import Iteratordef f(x): return 2 * x # 定义一个函数t_list = [1, 2, 3, 4, 5]function = map(f, t_list)print(isinstance(function, Iterator))# print(function.__next__())function.__next__()for i in function: print(i)#输出True46810
立即学习“Python免费学习笔记(深入)”;
3.reduce(function,iterable)
reduce把一个函数作用在一个可迭代序列,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
reduce函数在python3中已经不属于build-in了,而是在functools模块下,如需使用,需要从functools模块中引入
from functools import reducef = reduce(lambda x, y: x*y, [1, 2, 4])print(f)#输出8
4.hex(x)
把一个数字转成16进制
>>> hex(23)'0x17'
立即学习“Python免费学习笔记(深入)”;
5.range(stop)、range(start,stop,[step])
生成一个可迭代对象
>>> from collections import Iterator>>> isinstance(range(5),Iterator)False>>> from collections import Iterable>>> isinstance(range(5),Iterable)True>>> f.__next__Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'range' object has no attribute '__next__'>>> for i in f:... print(i)...01234# range(x) 是一个可迭代对象,而不是一个迭代器</module></stdin>
立即学习“Python免费学习笔记(深入)”;
6. isinstance(object, classinfo)
判断一个序列是否为可迭代对象或者迭代器
7.list([iterable])
把其他序列转换成一个列表
>>> list((1,2,3,4,5)) #把一个元组转换为一个列表[1, 2, 3, 4, 5]
立即学习“Python免费学习笔记(深入)”;
8.repr(object)
把代码转成字符串对象,没什么用,这边忽略
9.slice(stop),slice(start, stop[, step])
序列的切片
>>> a = [1,2,3,4,5,6]>>> a[slice(1,3)][2, 3]>>> a[1:3][2, 3]
立即学习“Python免费学习笔记(深入)”;
10.sorted(iterable[, key][, reverse])
>>> sorted([5,3,2,6,8])[2, 3, 5, 6, 8]>>> a = {1:5,6:8,3:6}>>> sorted(a) #默认是按key排序[1, 3, 6]>>> sorted(a.items()) #按key排序[(1, 5), (3, 6), (6, 8)]>>> sorted(a.items(),key = lambda x:x[1]) #按value排序[(1, 5), (3, 6), (6, 8)]
立即学习“Python免费学习笔记(深入)”;
11.reverse()
用于反向列表中元素,该方法没有返回值,但是会对列表的元素进行反向排序。
a = [1,2,4,5,3,7] a.reverse()a[7, 3, 5, 4, 2, 1]
立即学习“Python免费学习笔记(深入)”;