内置函数2

第二部分的内置函数信息

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

1.filter(function,iterable)

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

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(functioniterable)

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

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模块中引入

from functools import reduce

f = reduce(lambda x, y: x*y, [1, 2, 4])

print(f)

#输出
8

 

4.hex(x)

把一个数字转成16进制

>>> hex(23)
'0x17'

  

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)
...
0
1
2
3
4

# range(x) 是一个可迭代对象,而不是一个迭代器

  

6. isinstance(object, classinfo)

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

7.list([iterable])

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

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

  

8.repr(object)

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

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

序列的切片

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

  

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)]

  

 11.reverse()

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

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

  

原文地址:https://www.cnblogs.com/bigberg/p/7128079.html