时间:2021-07-01 10:21:17 帮助过:48人阅读
通过function过滤条件,去获取iterable中你想要的数据。
输出 True 6 9
- 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 4 6 8 10
- 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)
- #
reduce把一个函数作用在一个可迭代序列,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
reduce函数在python3中已经不属于build-in了,而是在functools模块下,如需使用,需要从functools模块中引入
输出 8
- from functools import reduce
- f = reduce(lambda x, y: x*y, [1, 2, 4])
- print(f)
- #
把一个数字转成16进制
- >>> hex(23)
- '0x17'
生成一个可迭代对象
- >>> 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
- # range(x) 是一个可迭代对象,而不是一个迭代器
判断一个序列是否为可迭代对象或者迭代器
把其他序列转换成一个列表
- >>> list((1,2,3,4,5)) #把一个元组转换为一个列表
- [1, 2, 3, 4, 5]
把代码转成字符串对象,没什么用,这边忽略
序列的切片
- >>> a = [1,2,3,4,5,6]
- >>> a[slice(1,3)]
- [2, 3]
- >>> a[1:3]
- [2, 3]
- >>> 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)]
用于反向列表中元素,该方法没有返回值,但是会对列表的元素进行反向排序。
- a = [1,2,4,5,3,7]
- a.reverse()
- a
- [7, 3, 5, 4, 2, 1]
以上就是python3中内置函数介绍的详细内容,更多请关注Gxl网其它相关文章!