jackyrar 发表于 2018-8-14 13:11:25

Python 函数 filter() map() reduce()

  1.filter(bool_func,seq)
  filter()是‘筛选函数’,也接收一个函数和一个序列,filter()把传人的函数依次作用于序列的每个元素,然后根据返回值是True还是false决定保留还是丢弃该元素
  例子:

[*]  def fr(x):
[*]  return x%2==1
[*]  print 'filter1:',filter(fr,range(1,51))#筛选出100以内的所有奇数
[*]  print 'filter2:',filter(fr,)
  输出:
  filter1:
  filter2:
  filter内建函数的Python实现:

[*]  >>> def filter(bool_func,seq):
[*]  filtered_seq = []
[*]  for eachItem in seq:
[*]  if bool_func(eachItem):
[*]  filtered_seq.append(eachItem)
[*]  return filtered_seq
  2、map(func,seq1[,seq2...])
  map():将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表。

[*]  >>> map(lambda x : None,)
[*]  
[*]  >>> map(lambda x : x * 2,)
[*]  
[*]  >>> map(lambda x : x * 2,])
[*]  ]
[*]  >>> map(lambda x : None,)
[*]  
  map内建函数的python实现:

[*]  >>> def map(func,seq):
[*]  mapped_seq = []
[*]  for eachItem in seq:
[*]  mapped_seq.append(func(eachItem))
[*]  return mapped_seq
  3.reduce(func,seq[,init])
  reduce():func为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素。

[*]  >>> reduce(lambda x,y : x + y,)
[*]  10
[*]  >>> reduce(lambda x,y : x + y,,10)
[*]  20
  reduce的python实现:

[*]  >>> def reduce(bin_func,seq,initial=None):
[*]  lseq = list(seq)
[*]  if initial is None:
[*]  res = lseq.pop(0)
[*]  else:
[*]  res = initial
[*]  for eachItem in lseq:
[*]  res = bin_func(res,eachItem)
[*]  return res
页: [1]
查看完整版本: Python 函数 filter() map() reduce()