简体   繁体   English

如果字符串少于 x 个字符,从字符串中删除最后一个单词的最高效计算方法是什么?

[英]Most computationally efficient way to remove last word from string if it's less than x number of characters?

My current solution is for x=3我目前的解决方案是 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" “永远的第二个”

Is there something more computationally efficient?有没有计算效率更高的东西?

You can try this:你可以试试这个:

def fun2(input):
  s = input.rsplit(' ', 1)
  return s[0] if len(s[1]) < 3 else input

Time profiling using %timeit :使用%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 is faster because rsplit is slightly faster and it avoids redundant computation. fun2更快,因为rsplit稍快一些,并且避免了冗余计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将唯一数字映射到列表列中每个唯一字符串的最有效的计算方法 - Most computationally efficient way to map a unique number to each unique string in a column of lists 如果附加变量为“ None”,则防止附加到字符串的最有效的计算方法 - Most computationally efficient way to prevent appending to string if appending variable is `None` 从字符串的开头删除数字的最Pythonic方法是什么? - What's the most Pythonic way to remove a number from start of a string? 删除列表最后一个元素的最有效方法是什么? - Most efficient way to remove last element of list? 寻找数字最后一位数的最有效方法是什么? - Most efficient way to look for the last digit of a number? 从字符串中删除特定单词的最有效方法 - Most efficient way to remove specific words from a string 从字符串中删除多个子字符串的最有效方法? - Most efficient way to remove multiple substrings from string? Pandas:将连续行与条件相结合的计算效率最高的方法 - Pandas: Most computationally efficient way to combine consecutive rows with conditions 从字符串中删除字符并创建子字符串的最pythonic方法是什么? - What is the most pythonic way to remove characters from a string and create substrings? Python - 删除少于“x”个字符的行,同时保留空行 - Python - Remove line with less than "x" number of characters while preserving blank lines
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM