簡體   English   中英

如果字符串少於 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)

“第一”

fun(b)

“永遠的第二個”

有沒有計算效率更高的東西?

你可以試試這個:

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稍快一些,並且避免了冗余計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM