我试图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有哪些改进使其更快?
这是我的代码.我不确定我是否需要一个计数器才能工作.答案应该是'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)