内置函数的补充说明

bin(x)

将整数x转换为'0b'开头的二进制数

1 >>> bin(3)
2 '0b11'
3 >>> bin(-10)
4 '-0b1010'
View Code

不需要'0b'的方法

1 >>> format(14, '#b'), format(14, 'b')
2 ('0b1110', '1110')
3 >>> f'{14:#b}', f'{14:b}'
4 ('0b1110', '1110')
View Code

其他进制转换的类似用法

1 >>> '%#o' % 10, '%o' % 10
2 ('0o12', '12')
3 >>> format(10, '#o'), format(10, 'o')
4 ('0o12', '12')
5 >>> f'{10:#o}', f'{10:o}'
6 ('0o12', '12')
View Code

 

filter(function, iterable)

容器iterable的元素挨个传给函数funciton,filter过滤掉不满足function的元素,满足funtion的元素构建一个新的迭代器。

function只能有一个参数。

可以使用list() set() tuple()确定迭代器类型。

1 def cute(x):
2     return x > 0
3 
4 
5 print("result is ", list(filter(cute, [-5, -3, -1, 1, 3, 5])))
View Code

输出:

1 result is  [1, 3, 5]
View Code

更多示例

 1 示例一:
 2 def cute(x):
 3     return x ** 3
 4 
 5 
 6 print("result is ", list(filter(cute, [-5, -3, -1, 1, 3, 5])))
 7 
 8 输出:
 9 result is  [-5, -3, -1, 1, 3, 5]
10 
11 
12 
13 示例二:
14 print(list(filter(lambda x: x*2, [-1, 1, -2, 2, -3, 3])))
15 输出:
16 [-1, 1, -2, 2, -3, 3]
17 
18 示例三:
19 print(list(filter(lambda x: x*"*", [-1, 1, -2, 2, -3, 3])))
20 输出:
21 [1, 2, 3]
View Code

 

map(function, iterable, ...)

多个容器iterable的元素并行传给函数funciton,function的计算结果构建一个新的迭代器。

funciton可以有多个参数,相应的iterable也要有相同个数。

可以使用list() set() tuple()确定迭代器类型。

1 def cute(x):
2     return x ** 3
3 
4 
5 print("filter is ", list(filter(cute, [-5, -3, -1, 1, 3, 5])))
6 print("map is ", list(map(cute, [-5, -3, -1, 1, 3, 5])))
View Code

输出:

1 filter is  [-5, -3, -1, 1, 3, 5]
2 map is  [-125, -27, -1, 1, 27, 125]
View Code

更多示例

 1 >>> print(list(filter(lambda x: x*"*", [-1, 1, -2, 2, -3, 3])))
 2 [1, 2, 3]
 3 >>> print(list(map(lambda x: x*"*", [-1, 1, -2, 2, -3, 3])))
 4 ['', '*', '', '**', '', '***']
 5 
 6 
 7 >>> print("filter:", list(filter(lambda x: x>0, [-3, -2, 0, 1, 2, 3])))
 8 filter: [1, 2, 3]
 9 >>> print("map:", list(map(lambda x: x>0, [-3, -2, 0, 1, 2, 3])))
10 map: [False, False, False, True, True, True]
View Code

 

lambda x: x > 0本质上是一个返回布尔值的函数。

posted on 2020-02-07 14:59  Rita_Jia  阅读(115)  评论(0)    收藏  举报

导航