The map function in Python is very useful. it has appeared in both character conversion and character traversal. now, what kind of surprises will it bring to us? Do you want to tell us that map is very good, and you need to find it more soon? Specific instance
We need to traverse the Directory, including sub-directories (haha) to find all the files with the suffix rmvb, avi, and pmp. (Day ?! What are you doing? This is my privacy ~~)
The code is as follows:
Import OS
Def anyTrue (predicate, sequence ):
Return True in map (predicate, sequence)
Def filterFiles (folder, exts ):
For fileName in OS. listdir (folder ):
If OS. path. isdir (folder + '/' + fileName ):
FilterFiles (folder + '/' + fileName, exts)
Elif anyTrue (fileName. endswith, exts ):
Print fileName
Exts = ['. rmvb', '. avi','. pmp ']
FilterFiles ('/media/Personal/Movie', exts)
Output result
Let's see what's good:
[66 video www.66ys.cn] lost in season 4 04. rmvb
[Lost. Quarter 4th]. Lost. S04E00. rmvb
[Lost Season 4] [02nd sets] [Chinese subtitles]. rmvb
Episode 05th of Lost Season 4 [Chinese subtitles]. rmvb
Episode 06th of Lost Season 4 [Chinese subtitles]. rmvb
Episode 07th of Lost Season 4 [Chinese subtitles]. rmvb
Tianci Season 01. rmvb
Tianci, December 2nd, 02. rmvb
Godsend Season 03. rmvb
Godsend Season 04. rmvb
Tianji 2nd 05. rmvb
Film Empire (bbs.cnxp.com). Beautiful soul. A. Beautiful. Mind.2001.CD1. rmvb
(Too many. don't output them all ~~)
Extension
In CookBook, itertools. imap is provided to filter strings. Different from map, imap returns an iteration object, while map returns a list object. The code is as follows:
Import itertools
Def anyTrue (predicate, sequence ):
Return True in itertools. imap (predicate, sequence)
Def endsWith (s, * endings ):
Return anyTrue (s. endswith, endings)
Imap is equivalent:
Def imap (function, * iterables ):
Iterables = map (iter, iterables)
While True:
Args = [I. next () for I in iterables]
If function is None:
Yield tuple (args)
Else:
Yield function (* args)