Python天天美味(16) - 过滤字符串的技巧,map与itertools.imap

Python中的map函数非常有用,在字符转换和字符遍历两节都出现过,现在,它又出现了,会给我们带来什么样的惊喜呢?是不是要告诉我们,map是非常棒的,以后要多找它玩呢?

具体的实例

我们需要在目录中遍历,包括子目录(哈哈),找出所有后缀为:rmvb ,avi  ,pmp 的文件。(天哪?!你要干什么?这可是我的隐私啊~~)
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)

输出结果

来看看有什么好东东:
[66影视www.66ys.cn]迷失第四季04.rmvb
[迷失.第4季].Lost.S04E00.rmvb
[迷失Lost第四季][第02集][中文字幕].rmvb
《迷失Lost第四季》第05集[中文字幕].rmvb
《迷失Lost第四季》第06集[中文字幕].rmvb
《迷失Lost第四季》第07集[中文字幕].rmvb
天赐第2季01.rmvb
天赐第2季02.rmvb
天赐第2季03.rmvb
天赐第2季04.rmvb
天赐第2季05.rmvb

影视帝国(bbs.cnxp.com).美丽心灵.A.Beautiful.Mind.
2001 .CD1.rmvb
( ... 太多了,不要全输出来吧~~)

扩展

CookBook一书中,提供的是itertools.imap来实现对字符串的过滤。imap和map不同的是,imap返回的是一个iteration对象,而map返回的是一个list对象。代码如下:
import  itertools
def  anyTrue(predicate, sequence):
    
return  True  in  itertools.imap(predicate, sequence)
def  endsWith(s,  * endings):
    
return  anyTrue(s.endswith, endings)

imap 等价于:
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)


Python 天天美味系列(总)

Python 天天美味(14) - splitlines  

Python 天天美味(15) - Python正则表达式操作指南(re使用)(转)  

Python 天天美味(16) - 过滤字符串的技巧,map与itertools.imap  

Python 天天美味(17) - open读写文件  

Python 天天美味(18) - linecache.getline()读取文件中特定一行  

...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值