python高阶函数

1.map

map(function, iterable)

The map() function takes the form map(function, iterable) and applies function to each item in iterable to return a list in Python 2 or an iterable map object in Python 3, 将iterable中的每个元素作用与funciton函数 在py2中返回list, 在py3中返回可迭代的map对象

1
2
3
4
>>> map(lambda x: x + "bzz!", ["I think", "I'm good"])
<map object at 0x7fe7101abdd0>
>>> list(map(lambda x: x + "bzz!", ["I think", "I'm good"]))
['I thinkbzz!', "I'm goodbzz!"]

2.filter

filter(function or None, iterable)

The filter() function takes the form filter(function or None, iterable) and filters the items in iterable based on the result returned by function. This will return a list in Python 2 or an iterable filter object in Python 3: filter根据funciton的结果来过滤元素, 在py2中返回list, 在py3中返回可迭代的filter对象

1
2
3
4
5

>>> filter(lambda x: x.startswith("I "), ["I think", "I'm good"])
<filter object at 0x7f9a0d636dd0>
>>> list(filter(lambda x: x.startswith("I "), ["I think", "I'm good"]))
['I think']

3.reduce

reduce(function, sequence, initial=None)

func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值

py3中移除了,使用需要从functools中引用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>>from functools import reduce
>>>arr = [1, 2, 3, 4, 5]
>>>reduce(lambda x, y : x+y, arr)
15

# 自己实现
def reduce(func, seq, init_num=None):
    if init_num != None:
        res = init_num
    else:
        res = seq.pop(0)
    for i in seq:
        res = func(res, i)
    return res  

4.enumerate

enumerate(iterable[, start]) 返回index和对象

1
2
for i, item in enumerate(mylist):
    print("Item %d: %s" % (i, item))

5.sorted

sorted(iterable, key=None, reverse=False) 排序

1
2
3
4
>>> sorted([("a", 2), ("c", 1), ("d", 4)]) 
[('a', 2), ('c', 1), ('d', 4)]
>>> sorted([("a", 2), ("c", 1), ("d", 4)], key=lambda x: x[1]) 
[('c', 1), ('a', 2), ('d', 4)]

6.any

any(iterable)

7.all

all(iterable)

1
2
3
4
5
mylist = [0, 1, 3, -1] 
if all(map(lambda x: x > 0, mylist)):
    print("All items are greater than 0")
if any(map(lambda x: x > 0, mylist)):
    print("At least one item is greater than 0")

8.zip

zip(iter1 [,iter2 […]])

It takes multiple sequences and combines them into tuples. zip() returns a list in Python 2 and an iterable in Python 3

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 py2中返回list, py3中返回可迭代对象

1
2
3
4
5
6
7
8
>>> keys = ["foobar", "barzz", "ba!"]
<map object at 0x7fc1686100d0>
>>> zip(keys, map(len, keys))
<zip object at 0x7fc16860d440>
>>> list(zip(keys, map(len, keys)))
[('foobar', 6), ('barzz', 5), ('ba!', 3)]
>>> dict(zip(keys, map(len, keys))) 
{'foobar': 6, 'barzz': 5, 'ba!': 3}

9.next

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def first(predicate, items):
    for item in items:
        if predicate(item): 
            return item
first(lambda x: x > 0, [-1, 0, 1, 2])
	
# Less efficient, 可能为indexError
list(filter(lambda x: x > 0, [-1, 0, 1, 2]))[0] 
# Efficient 
next(filter(lambda x: x > 0, [-1, 0, 1, 2]))
	
>>a = range(10)
>>next((x for x in a if x > 10), 'default')
'default'

10.partial

partial(func, *args, **keywords)

偏函数 被用作 “冻结” 某些函数的参数或者关键字参数, 返回一个新的函数,调用这个新函数会更简单

1
2
3
4
5
6
7
from functools import partial 
from first import first

def greater_than(number, min=0):
    return number > min

first([-1, 0, 1, 2], key=partial(greater_than, min=42))

11.其余

参考itertools, functools