python filter map reduce

时间:2024-09-01 12:05:50
filter(function, iterable)
Construct a list from those elements of iterable for which function returns true.
  对iterable中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于iterable的类型)返回. iterable包括列表,iterator等。一个简单例子,过滤出一个整数列表中所有的奇数
>>> lst = [1,2,3,4,5,6,7]
>>> filter(lambda e: e % 2, lst)
[1, 3, 5, 7]
filter也有一个返回迭代器的版本:itertools.ifilter
filter完全可以用list comprehension实现 : [elem for elem in iterable if function(elem)]
map(function, iterable,...) :

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

  如果只有一个iterable,那么对iterable中的item依次执行function(item),见执行结果组成一个List返回。如果有多个iterable, 那么function需要同时接受多个参数。
  第一个例子将所有元素乘以2
>>> lst = [1,2,3,4,5,6,7]
>>> map(lambda e: e * 2, lst)
[2, 4, 6, 8, 10, 12, 14]
   第二个例子将两个序列的对应元素相加
>>> lst = [1,2,3,4,5,6,7]
>>> map(lambda e1, e2: e1 + e2, lst, (7, 6, 5, 4, 3, 2, 1))
[8, 8, 8, 8, 8, 8, 8]
map也有一个返回迭代器的版本:itertools.imap
对于只有一个iterable的版本 等价于 [function(item) for item in iterable]
对于多个iterable的版本 基本等价于[function(*items) for item in zip(*iterable)], 比如上面第二个例子等同于 [x + y for (x, y) in zip(lst0, lst1)]
但是对于多个序列长度不一致的情况,zip和map的处理是不一样的,zip以最短长度为准;map以最长长度为准,较短的序列用None填充
>>> zip((1,2,3), ('a', 'b'))
[(1, 'a'), (2, 'b')]
>>> map(lambda x, y:(x, y), (1,2,3), ('a', 'b'))
[(1, 'a'), (2, 'b'), (3, None)]
>>>
reduce(function, iterable, init_value)
Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value
  对iterable中的item顺序迭代调用function,如果有inti_value,还可以作为初始值调用。function接受两个参数,第一个参数,历史迭代值,第二参数,新的迭代元素。举个简单例子,对序列所有元素的平方求和:
>>> reduce(lambda x, y: x + y *y, (1, 2, 3), 0)
14
如果sequence中只有一个元素 且没有inti_value,那么会返回第一个元素
  笔者之前有一个简单需求:把多个list整合到一个list。for example:  [[1,2,3], [5], [5, 6]]  ===》》》 [1, 2, 3, 5, 5, 6]
  当时试过用filter map reduce来实现, 当然实现都不pythonic,直到后来发现了itertools.chain
 # -*- coding: utf-8 -*-
def test():
lst = [[1,2,3], [5], [5, 6]]
print ' ---- use filter ----'
ret = []
print filter(lambda e: ret.extend(e), lst)
print ret print ' ---- use map ----'
ret = []
print map(lambda e: ret.extend(e), lst)
print ret print ' ---- use reduce ----'
ret = reduce(lambda r, e: r.extend(e) or r, lst, [])
print ret print ' ---- use itertools.chain ----'
import itertools
print list(itertools.chain(*lst)) if __name__ == '__main__':
test()

最后,只要可以,尽量使用list comprehension