如果字符串少于 x 个字符,则从字符串中删除最后一个单词的计算效率最高的方法是什么?
Most computationally efficient way to remove last word from string if it's less than x number of characters?
我目前的解决方案是 x=3
a = "first one is"
b = "the second forever"
def fun(input):
if input.split()[-1] < 3:
return ' '.join( input.split()[0:-1])
else:
return input
fun(a)
"first one"
fun(b)
"The second forever"
有没有计算效率更高的东西?
你可以试试这个:
def fun2(input):
s = input.rsplit(' ', 1)
return s[0] if len(s[1]) < 3 else input
时间分析使用 %timeit
:
In [25]: def fun(input):
...: if len(input.split()[-1]) < 3:
...: return ' '.join( input.split()[0:-1])
...: else:
...: return input
...:
In [26]: def fun2(input):
...: s = input.rsplit(' ', 1)
...: return s[0] if len(s[1]) < 3 else input
...:
In [28]: fun(a), fun2(a)
Out[28]: ('first one', 'first one')
In [29]: %timeit fun(a)
433 ns ± 0.759 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
In [30]: %timeit fun2(a)
222 ns ± 1.04 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
fun2
更快,因为 rsplit
稍微快一点并且避免了冗余计算。
我目前的解决方案是 x=3
a = "first one is"
b = "the second forever"
def fun(input):
if input.split()[-1] < 3:
return ' '.join( input.split()[0:-1])
else:
return input
fun(a)
"first one"
fun(b)
"The second forever"
有没有计算效率更高的东西?
你可以试试这个:
def fun2(input):
s = input.rsplit(' ', 1)
return s[0] if len(s[1]) < 3 else input
时间分析使用 %timeit
:
In [25]: def fun(input):
...: if len(input.split()[-1]) < 3:
...: return ' '.join( input.split()[0:-1])
...: else:
...: return input
...:
In [26]: def fun2(input):
...: s = input.rsplit(' ', 1)
...: return s[0] if len(s[1]) < 3 else input
...:
In [28]: fun(a), fun2(a)
Out[28]: ('first one', 'first one')
In [29]: %timeit fun(a)
433 ns ± 0.759 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
In [30]: %timeit fun2(a)
222 ns ± 1.04 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
fun2
更快,因为 rsplit
稍微快一点并且避免了冗余计算。