几个常用的内置函数
1. filter 过滤函数
>>> def is_str(factor):
... return isinstance(factor, str)
...
>>> test_lines = [1, 2, 3, 'name', 'age', 4, 'sex']
>>> list(filter(is_str, test_lines))
['name', 'age', 'sex']
>>>
下面的列表表达式实现同样的功能:
>>> [x for x in test_lines if isinstance(x, str)]
['name', 'age', 'sex']
>>>
2. zip 拉链函数(姑且这么叫。。。)
>>> info = ['name', 'age', 'sex']
>>> attr = ['eclipse', 18, 'M']
>>> out = zip(info, attr)
>>> out
<zip object at 0x0000025519874048>
>>> for key, value in out:
... print("%s: %s" %(key, value))
...
name: eclipse
age: 18
sex: M
>>>
组合的两个列表或者元组的长度不同,以最短的那个截止:
>>> aa = ['a', 'b', 'c', 'd']
>>> bb = [1, 2, 3, 4, 5]
>>> for k, v in zip(aa, bb):
... print("%s: %s" %(k, v))
...
a: 1
b: 2
c: 3
d: 4
>>>
3. lambda 匿名函数
>>> ff = lambda x, y: x + y
>>> print(ff(2, 3))
5
>>>
对于那些可以传入key
的内置函数来说,可以用lambda
去筛选,比如我要取出价格最高的水果:
>>> dic = {'apple': 109, 'orange': 88, 'banana': 98, 'peach': 111}
>>> print(max(dic, key = lambda k: dic[k]))
peach
>>>
4. map 函数,我觉得这个函数就是映射
>>> list_ = [1, 3, 5, 7, 9]
>>> def square(x):
... return x**2
...
>>> list(map(square, list_))
[1, 9, 25, 49, 81]
>>>
5. 两个高级的用法,说是某个公司的面试题
将(('a'), ('b'))
和 (('c'), ('d'))
组合成[{'a': 'c', 'b': 'd'}]
>>> ret = zip((('a'), ('b')), (('c'), ('d')))
>>> out = map(lambda tup: {tup[0]: tup[1]}, ret)
>>> list(out)
[{'a': 'c'}, {'b': 'd'}]
>>>
>>> def multipliers():
... return (lambda x: i * x for i in range(4))
...
>>> print([m(2) for m in multipliers()])
[0, 2, 4, 6]
>>>