标签:
现有一文本,每行一条数据,实现这行数据中有所要关键字则打出这行
import sys with open(sys.argv[1]) as alls: alls2 = [_.strip() for _ in alls] for _ in alls2: if sys.argv[2] in _: print _
with open( sys.argv[1] ) as alls: results = [ _.strip() for _ in alls if sys.argv[2] in _.strip() ] print '\n'.join( results )
<pre name="code" class="python">with open( sys.argv[1] ) as alls: results = [ _.strip() for _ in alls if sys.argv[2] in _.strip() ]
for result in results: print result
print '\n'.join( results )打出时太快,没有瀑布的感觉,改成
for result in results: print result运行时间1.59 s居然慢了
后来用map函数改写
def fetch( _ ): _2 = _.strip() global searchP if searchP in _2: pass#print _2
居然更慢了,耗时2 s
用上虚拟函数吧
x = map( lambda _: _.strip() if searchP in _.strip() else None, alls )
最后兼顾美观与速度,用了filter函数
xs = filter( lambda _: True if searchP in _.strip() else False, alls ) for x in xs: if x: print x,耗时1.67 s,虽然还没传统的快,但技巧性已经提高了,效率就先放下吧。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u010211892/article/details/47700155