栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python

从效率的角度来看,你不会被击败

s.translate(None, string.punctuation)

对于更高版本的Python,请使用以下代码:

s.translate(str.maketrans('', '', string.punctuation))

它使用查找表在C中执行原始字符串操作-除了编写自己的C代码以外,没有什么比这更好的了。

如果不用担心速度,那么另一个选择是:

exclude = set(string.punctuation)s = ''.join(ch for ch in s if ch not in exclude)

这比每个char的

s.replace
更快,但效果不如regexes或
string.translate
等非纯python方法,如下面的时序所示。对于这种类型的问题,以尽可能低的水平进行操作会有所回报。

计时代码:

import re, string, timeits = "string. With. Punctuation"exclude = set(string.punctuation)table = string.maketrans("","")regex = re.compile('[%s]' % re.escape(string.punctuation))def test_set(s):    return ''.join(ch for ch in s if ch not in exclude)def test_re(s):  # From Vinko's solution, with fix.    return regex.sub('', s)def test_trans(s):    return s.translate(table, string.punctuation)def test_repl(s):  # From S.Lott's solution    for c in string.punctuation:        s=s.replace(c,"")    return sprint "sets      :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)print "regex     :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)print "replace   :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

得到以下结果:

sets      : 19.8566138744regex     : 6.86155414581translate : 2.12455511093replace   : 28.4436721802


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/370797.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号