SoFunction
Updated on 2024-10-29

5 Ways to Compare the Performance of Python String Filtering

Python String Filtering Performance Comparison 5 Methods Comparison

Compare 5 methods in total. Look directly at the code:

import random
import time
import os
import string

base = +
total = 100000

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

def regular(ss):
  """Regular expressions."""
  import re
  rt = (r'\D', '', ss)
  return rt

def filter_mt(ss):
  """Functional"""
  return filter(lambda c:(), ss)

def list_com(ss):
  """List Generator"""
  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):
  """()"""
  table = ('', '')
  ss = (table,)
  return ss

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

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

Thanks for reading, I hope this helps, and thanks for supporting this site!