python内置高阶函数
- Filter函数
-
filter(function, sequence) -> list, tuple, or string
,会对指定序列执行过滤操作。 -
对字符串/列表/元组等
sequence
类型进行过滤,sequence
中的item
依次执行function(item)
-
将执行结果为
True
的item
组成一个List/String/Tuple
(取决于sequence
的类型)返回def odds(x): return x%2==0 print filter(odds, range(1, 101)) //返回列表,包含1~100的偶数,1%2 == False,不计入,2%2==0 True,计入...
-
- Map函数
-
map(function, iterable[, iterable, ...]) -> list
,根据提供的函数对指定序列做映射 -
对
iterable
中的item
依次执行function(item)
映射,执行结果输出为list
def mul3(a): return a*3 L = range(0, 11) print 'list is ', L //L is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],key=1,2,3...10 print 'L mapping ', map(mul3, L) //L mapping [3, 6, 9, 12, 15, 18, 21, 24, 27, 30],value=1*3, 2*3, ...
-
- Reduce函数
-
reduce(function, sequence[, initial]) -> value
,对参数序列sequence
中元素进行累积 -
依次从
sequence
中取一个元素,和上一次调用function
的结果做参数再次调用function
def add(x, y): return x+y print reduce(add, range(1, 11), 0) //0+1, 1+2, 3+4,...55, f(f(f(f(a, b), c), d)...)
-
统计文章中哪些词汇出现的频率最高
- 统计文章中,单词出现的次数
- 需要注意单词的格式化,去除特殊符号和单词大小写对相同单词的影响
- 过程中的数据可用列表/元组方法操作,最后转换为字典即可
- 重复操作多篇文章
- 应用高阶函数
map(function, iterable[, iterable, ...]) -> list
完成关系映射,生成每篇文章的词频统计数据
- 应用高阶函数
- 将所有文章统计后汇总
-
应用高阶函数
reduce(function, sequence[, initial]) -> value
完成累积操作,对每篇文章的词频进行汇总,相同项求和,不同项加入总的词频数据# coding: utf-8 def readFile(filename): //统计一篇文章中的单词和词频,返回二者构成的元组列表 f = open(filename, 'r') washlist = [] //单词格式化后的列表 savedlist = [] //已经存入词频列表的单词 freqlist = [] //词频列表 for line in f: wordlist = line.lower().strip().split() //格式化,去除头尾空白字符,并分割为待清洗的单词列表 for word in wordlist: lastchar = word[-1] //待清洗单词列表的每个单词的词尾 firstchar = word[0] //待清洗单词列表的每个单词的词头 if lastchar in ["!", ".", ";", "\"", "\'"]: //判断词尾是否有特殊字符 word = word.strip(lastchar) elif firstchar in ["!", ".", ";", "\"", "\'"]: //判断词头是否有特殊字符 word = word.strip(firstchar) washlist.append(word) //清洗了特殊字符的单词列表 for word in washlist: //统计清洗后列表中的词频,用到列表的count方法 if not word in wordsaved: count = washlist.count(word) wordsaved.append(word) freqlist.append((word, count)) //将单词和词频的元组构成列表 f.close() return freqlist def merge(listA, listB): mergelist = [] wordA, countA = zip(*listA) //返回列表A的单词和词频分别构成的元组 wordB, countB = zip(*listB) //返回列表B的单词和词频分别构成的元组 for word, count in listB: //遍历有单词和词频元组构成的列表B if word in wordA: //如果单词在列表A中存在,合并二者的词频数据,将单词和新的词频放入合并后的元组列表mergelist中 count = countA[wordA.index(word)] + count mergelist.append((word, count)) for word, count in listA: //再讲只存在列表A的单词和词频的元组放入mergelist中 if not word in wordB: mergelist.append((word, count)) return mergelist if __name__ == '__main__': files = ["article_000.txt", "article_001.txt", "article_002.txt", "article_003.txt", "article_004.txt", "article_005.txt"] freqlist = map(readFile, files) ##return the (word,count) list for each articals totallist = reduce(merge, freqlist) ##merge each wordlist of artical
-
参考资料
1.从两个例子看 Python【map、reduce、filter】内置函数的使用
2.[Python] 函数lambda(), filter(), map(), reduce()
3.python中的map、filter、reduce函数
网友评论