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

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

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%,效果不错

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,虽然还没传统的快,但技巧性已经提高了,效率就先放下吧。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值