python字符串过滤性能比较5种方法

作者:lqh 时间:2021-09-26 18:35:25 

python字符串过滤性能比较5种方法比较

总共比较5种方法。直接看代码:


import random
import time
import os
import string

base = string.digits+string.punctuation
total = 100000

def loop(ss):
 """循环"""
 rt = ''
 for c in ss:
   if c in '0123456789':
     rt = rt + c
 return rt

def regular(ss):
 """正则表达式"""
 import re
 rt = re.sub(r'\D', '', ss)
 return rt

def filter_mt(ss):
 """函数式"""
 return filter(lambda c:c.isdigit(), ss)

def list_com(ss):
 """列表生成式"""
 isdigit = {'0': 1, '1': 1, '2': 1, '3': 1, '4': 1,
           '5':1, '6':1, '7':1, '8':1, '9':1}.has_key
 return ''.join([x for x in ss if isdigit(x)])

def str_tran(ss):
 """string.translate()"""
 table = string.maketrans('', '')
 ss = ss.translate(table,string.punctuation)
 return ss

if __name__ == '__main__':
 lst = []
 for i in xrange(total):
   num = random.randrange(10, 50)
   ss = ''
   for j in xrange(num):
     ss = ss + random.choice(base)
   lst.append(ss)

s1 = time.time()
 map(loop,lst)
 print "loop: ",time.time() - s1
 print '*'*20
 s1 = time.time()
 map(regular, lst)
 print "regular: ", time.time() - s1
 print '*' * 20
 s1 = time.time()
 map(str_tran, lst)
 print "str_tran: ", time.time() - s1
 print '*' * 20
 s1 = time.time()
 map(filter_mt, lst)
 print "filter_mt: ", time.time() - s1
 print '*' * 20
 s1 = time.time()
 map(list_com, lst)
 print "list_com: ", time.time() - s1

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

标签:python,字符串,过滤
0
投稿

猜你喜欢

  • Python 中@lazyprop 装饰器的用法

    2022-11-30 16:42:10
  • JavaScript中随机数方法 Math.random()

    2024-04-10 13:56:30
  • mysql 5.7.14 下载安装、配置与使用详细教程

    2024-01-15 14:39:25
  • Go语言实现登录验证代码案例

    2024-05-08 10:24:14
  • 基于Bootstrap实现下拉菜单项和表单导航条(两个菜单项,一个下拉菜单和登录表单导航条)

    2024-04-16 08:49:09
  • django的403/404/500错误自定义页面的配置方式

    2023-01-19 06:44:40
  • python处理json字符串(使用json.loads而不是eval())

    2023-06-13 11:50:39
  • python写入中英文字符串到文件的方法

    2022-11-21 23:11:03
  • XAMPP和Mysql共存的方法

    2010-12-03 16:34:00
  • js修改原型的属性使用介绍

    2024-04-10 10:51:03
  • python编写暴力破解FTP密码小工具

    2021-11-29 15:32:40
  • Python字典fromkeys()方法使用代码实例

    2021-07-09 09:54:38
  • Oracle 9i产品文档

    2010-07-16 13:35:00
  • python 删除excel表格重复行,数据预处理操作

    2023-04-19 06:10:33
  • Go gRPC环境安装教程示例详解

    2024-02-17 06:48:36
  • python中的信号通信 blinker的使用小结

    2023-07-31 10:05:10
  • FCKeditor技巧之在按钮旁边加文字

    2007-10-10 13:17:00
  • 教你利用Python破解ZIP或RAR文件密码

    2022-04-25 07:11:15
  • MySQL8.0.27安装过程中卡在Initializing Database中并报错的解决

    2024-01-19 06:35:05
  • 无闪烁更新网页内容JS实现

    2024-05-09 10:37:18
  • asp之家 网络编程 m.aspxhome.com