当前位置:Gxlcms > Python > python3中内置函数介绍

python3中内置函数介绍

时间:2021-07-01 10:21:17 帮助过:48人阅读

在python3 中,filter、map、reduce已经不是内置函数,即<build-in function>,python3中三者是class,返回结果变成了可迭代的对象

1.filter(function,iterable)

通过function过滤条件,去获取iterable中你想要的数据。

  1. from collections import Iterator
  2. test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  3. f = filter(lambda x: x % 3 == 0, test_list)
  4. # filter 得到的是一个迭代器
  5. print(isinstance(f, Iterator))
  6. f.__next__()
  7. for i in f:
  8. print(i)
  9. #
输出 True 6 9

  

2.map(function, iterable)

接受一个函数和可迭代对象(如列表等),将函数依次作用于序列的每一个元素,形成一个新的迭代器。

  1. from collections import Iterator
  2. def f(x):
  3. return 2 * x # 定义一个函数
  4. t_list = [1, 2, 3, 4, 5]
  5. function = map(f, t_list)
  6. print(isinstance(function, Iterator))
  7. # print(function.__next__())
  8. function.__next__()
  9. for i in function:
  10. print(i)
  11. #
输出 True 4 6 8 10

  

3.reduce(function,iterable)

reduce把一个函数作用在一个可迭代序列,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

reduce函数在python3中已经不属于build-in了,而是在functools模块下,如需使用,需要从functools模块中引入

  1. from functools import reduce
  2. f = reduce(lambda x, y: x*y, [1, 2, 4])
  3. print(f)
  4. #
输出 8

 

4.hex(x)

把一个数字转成16进制

  1. >>> hex(23)
  2. '0x17'

  

5.range(stop)、range(start,stop,[step])

生成一个可迭代对象

  1. >>> from collections import Iterator
  2. >>> isinstance(range(5),Iterator)
  3. False
  4. >>> from collections import Iterable
  5. >>> isinstance(range(5),Iterable)
  6. True
  7. >>> f.__next__
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. AttributeError: 'range' object has no attribute '__next__'
  11. >>> for i in f:
  12. ... print(i)
  13. ...
  14. 0
  15. 1
  16. 2
  17. 3
  18. 4
  19. # range(x) 是一个可迭代对象,而不是一个迭代器

  

6. isinstance(object, classinfo)

判断一个序列是否为可迭代对象或者迭代器

7.list([iterable])

把其他序列转换成一个列表

  1. >>> list((1,2,3,4,5)) #把一个元组转换为一个列表
  2. [1, 2, 3, 4, 5]

  

8.repr(object)

把代码转成字符串对象,没什么用,这边忽略

9.slice(stop),slice(start, stop[, step])

序列的切片

  1. >>> a = [1,2,3,4,5,6]
  2. >>> a[slice(1,3)]
  3. [2, 3]
  4. >>> a[1:3]
  5. [2, 3]

  

10.sorted(iterable[, key][, reverse])

  1. >>> sorted([5,3,2,6,8])
  2. [2, 3, 5, 6, 8]
  3. >>> a = {1:5,6:8,3:6}
  4. >>> sorted(a) #默认是按key排序
  5. [1, 3, 6]
  6. >>> sorted(a.items()) #按key排序
  7. [(1, 5), (3, 6), (6, 8)]
  8. >>> sorted(a.items(),key = lambda x:x[1]) #按value排序
  9. [(1, 5), (3, 6), (6, 8)]

  

11.reverse()

用于反向列表中元素,该方法没有返回值,但是会对列表的元素进行反向排序。

  1. a = [1,2,4,5,3,7]
  2. a.reverse()
  3. a
  4. [7, 3, 5, 4, 2, 1]

  

以上就是python3中内置函数介绍的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行