码迷,mamicode.com
首页 > 编程语言 > 详细

【python】查找字符串时哪一种写法出结果速度更快?

时间:2015-08-16 10:48:30      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

现有一文本,每行一条数据,实现这行数据中有所要关键字则打出这行

import sys

with open(sys.argv[1]) as alls:
	alls2 = [_.strip() for _ in alls]

for _ in alls2:
	if sys.argv[2] in _:
		print _

一开始我是这么写的,后来觉得既不美观,速度又慢(运行花了2.31 s),进行了改写

with open( sys.argv[1] ) as alls:
	results = [ _.strip() for _ in alls if sys.argv[2] in _.strip() ]
	print '\n'.join( results )

运行耗时1.54 s,快了34%,效果不错

<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

map( fetch, list)

居然更慢了,耗时2 s

用上虚拟函数吧

x = map( lambda _: _.strip() if searchP in _.strip() else None, alls )

噩梦啊,更慢了 2.1 s

最后兼顾美观与速度,用了filter函数

	xs = filter( lambda _: True if searchP in _.strip() else False, alls )
	for x in xs:
		if x:
			print x,
耗时1.67 s,虽然还没传统的快,但技巧性已经提高了,效率就先放下吧。

版权声明:本文为博主原创文章,未经博主允许不得转载。

【python】查找字符串时哪一种写法出结果速度更快?

标签:

原文地址:http://blog.csdn.net/u010211892/article/details/47700155

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!