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

yipeiwu_com6年前Python基础

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利用Beautiful Soup模块修改内容方法示例

前言 其实Beautiful Soup 模块除了能够搜索和导航之外,还能够修改 HTML/XML 文档的内容。这就意味着能够添加或删除标签、修改标签名称、改变标签属性值和修改文本内容等等...

Python格式化输出%s和%d

Python格式化输出%s和%d

本文介绍了Python格式化输出%s和%d的实例案例。分享给大家供大家参考,具体如下: python print格式化输出 1. 打印字符串 print ("His name is %s...

ansible作为python模块库使用的方法实例

前言 ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量...

用 Python 爬了爬自己的微信朋友(实例讲解)

用 Python 爬了爬自己的微信朋友(实例讲解)

最近几天干啥都不来劲,昨晚偶然了解到 Python 里的 itchat 包,它已经完成了 wechat 的个人账号 API 接口,使爬取个人微信信息更加方便。鉴于自己很早之前就想知道诸如...

对Python subprocess.Popen子进程管道阻塞详解

问题产生描述 使用子进程处理一个大的日志文件,并对文件进行分析查询,需要等待子进程执行的输出结果,进行下一步处理。 出问题的代码 # 启用子进程执行外部shell命令 def __s...