python字串過濾效能比較5種方法

2022-10-04 21:06:40 字數 1688 閱讀 2246

python字串過濾效能比較5種方法比較

總共比較5種方法。直接看**:

import random

import time

iuddzkoaiyomport 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 uddzkoaiyofilter_mt(ss):

"""函式式"""

return filter(lambda c:c.isdigit(), ss)

def list_com(ss):

"""列表生成式"""

isdigit = .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字串過濾效能比較5種方法

本文位址: /jiaoben/python/194354.html

字串拷貝函式的效能比較

先上結論 memcpy效能 優於 snprintf效能 優於 strncpy效能 memcpy效能略優於snprintf,strncpy比前兩者慢的非常多,基本上是撈不回來了。編譯器 gcc version 3.4.5 a little old fashion 沒有編譯器優化 測試 int strn...

JavaScript 字串連線效能比較

先上結果 使用方法 執行次數 連線耗時 1 0.069ms concat 10.114ms array.join 10.149ms 模板字串 10.051ms 使用方法 執行次數 連線耗時 100 0.011ms concat 1000.028ms array.join 1000.056ms 模板字...

Oracle 日期過濾方法效能比較

string sql select from 表 where 時間列 between to date gos.tostring yyyy mm dd hh mm ss yyyy mm dd hh24 mi ss and to date ends.tostring yyyy mm dd hh mm s...