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

yipeiwu_com5年前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画一个玫瑰和一个爱心

节日用心准备的礼物,使用python画玫瑰和爱心,供大家参考,具体内容如下 #!/usr/bin/env python #coding=utf-8 #女生节礼物 import r...

python中的编码知识整理汇总

问题 在平时工作中,遇到了这样的错误: UnicodeDecodeError: 'ascii' codec can't decode byte 想必大家也都碰到过,很常见 。于是...

Python中实现常量(Const)功能

python语言本身没有提供const,但实际开发中经常会遇到需要使用const的情形,由于语言本身没有这种支出,因此需要使用一些技巧来实现这一功能 定义const类如下 复制代码 代码...

python requests模拟登陆github的实现方法

python requests模拟登陆github的实现方法

1. Cookie 介绍 HTTP 协议是无状态的。因此,若不借助其他手段,远程的服务器就无法知道以前和客户端做了哪些通信。Cookie 就是「其他手段」之一。 Cookie 一个典型的...

新手如何发布Python项目开源包过程详解

新手如何发布Python项目开源包过程详解

本文假设你在 GitHub 上已经有一个想要打包和发布的项目。 第 0 步:获取项目许可证 在做其他事之前,由于你的项目要开源,因此应该有一个许可证。获取哪种许可证取决于项目包的使用方式...