相关疑难解决方法(0)

与Python 3.4相比,为什么Python 3.5中的str.translate要快得多?

我试图text.translate()在Python 3.4中删除给定字符串中不需要的字符.

最小的代码是:

import sys 
s = 'abcde12345@#@$#%$'
mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$')
print(s.translate(mapper))
Run Code Online (Sandbox Code Playgroud)

它按预期工作.但是,在Python 3.4和Python 3.5中执行相同的程序会产生很大的差异.

计算时间的代码是

python3 -m timeit -s "import sys;s = 'abcde12345@#@$#%$'*1000 ; mapper = dict.fromkeys(i for i in range(sys.maxunicode) if chr(i) in '@#$'); "   "s.translate(mapper)"
Run Code Online (Sandbox Code Playgroud)

Python 3.4程序需要1.3毫秒,而Python 3.5中的相同程序只需要26.4μs.

与Python 3.4相比,Python 3.5有哪些改进使其更快?

python string python-3.x python-internals python-3.5

116
推荐指数
1
解决办法
1万
查看次数

从Python中的字符串中删除辅音

这是我的代码.我不确定我是否需要一个计数器才能工作.答案应该是'iiii'.

def eliminate_consonants(x):
        vowels= ['a','e','i','o','u']
        vowels_found = 0
        for char in x:
            if char == vowels:
                print(char)

eliminate_consonants('mississippi')
Run Code Online (Sandbox Code Playgroud)

python string list python-idle python-3.x

3
推荐指数
2
解决办法
3794
查看次数