本文摘自php中文网,作者零下一度,侵删。
在python3 中,filter、map、reduce已经不是内置函数,即<build-in function>,python3中三者是class,返回结果变成了可迭代的对象1.filter(function,iterable)
通过function过滤条件,去获取iterable中你想要的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | from collections import Iterator
test_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)
#输出
True
6
9
|
2.map(function, iterable)
接受一个函数和可迭代对象(如列表等),将函数依次作用于序列的每一个元素,形成一个新的迭代器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | from collections import Iterator
def 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)
#输出
True
4
6
8
10
|
3.reduce(function,iterable)
reduce把一个函数作用在一个可迭代序列,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
reduce函数在python3中已经不属于build-in了,而是在functools模块下,如需使用,需要从functools模块中引入
1 2 3 4 5 6 7 8 | from functools import reduce
f = reduce(lambda x, y: x*y, [1, 2, 4])
print(f)
#输出
8
|
4.hex(x)
把一个数字转成16进制
5.range(stop)、range(start,stop,[step])
生成一个可迭代对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | >>> 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)
...
0
1
2
3
4
|
6. isinstance(object, classinfo)
判断一个序列是否为可迭代对象或者迭代器
7.list([iterable])
把其他序列转换成一个列表
1 2 | >>> list (( 1 , 2 , 3 , 4 , 5 ))
[ 1 , 2 , 3 , 4 , 5 ]
|
8.repr(object)
把代码转成字符串对象,没什么用,这边忽略
9.slice(stop),slice(start, stop[, step])
序列的切片
1 2 3 4 5 | >>> a = [ 1 , 2 , 3 , 4 , 5 , 6 ]
>>> a[ slice ( 1 , 3 )]
[ 2 , 3 ]
>>> a[ 1 : 3 ]
[ 2 , 3 ]
|
10.sorted(iterable[, key][, reverse])
1 2 3 4 5 6 7 8 9 | >>> sorted ([ 5 , 3 , 2 , 6 , 8 ])
[ 2 , 3 , 5 , 6 , 8 ]
>>> a = { 1 : 5 , 6 : 8 , 3 : 6 }
>>> sorted (a)
[ 1 , 3 , 6 ]
>>> sorted (a.items())
[( 1 , 5 ), ( 3 , 6 ), ( 6 , 8 )]
>>> sorted (a.items(),key = lambda x:x[ 1 ])
[( 1 , 5 ), ( 3 , 6 ), ( 6 , 8 )]
|
11.reverse()
用于反向列表中元素,该方法没有返回值,但是会对列表的元素进行反向排序。
1 2 3 4 | a = [ 1 , 2 , 4 , 5 , 3 , 7 ]
a.reverse()
a
[ 7 , 3 , 5 , 4 , 2 , 1 ]
|
以上就是python3中内置函数介绍的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
巧妙解决Python多线程死锁问题
Python如何删除字符串中所有空格
Python装饰器定义及运用实例讲解
Python安装路径怎么找
Python实现简单的httpserver服务器
Python学习-----类的封装、继承,多态
Python中pop()函数如何使用
Python中的对象属性如何访问?两种方法实例解析
Python--条件语句与循环语句
女生学Python难吗
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python3中内置函数介绍