哪种方法可以更快地计算不带空格的字符数?
哪个更pythonic?

def sent_length(sentence):
  return sum(1 for c in sentence if c != ' ')


要么

def sent_length(sentence):
  return len(sentence.replace(" ", ""))


要么

import re
pattern = re.compile(r'\s+')

def sent_length(sentence):
  return len(re.sub(pattern, '', sentence))

最佳答案

您可以从python -m timeit获取计时:

[matt tmp] python -m timeit "sum(1 for c in 'blah blah blah' if c != ' ')"
100000 loops, best of 3: 2.96 usec per loop
[matt benchmark] python -m timeit -s "import re; pattern = re.compile(r'\s+')" "len(pattern.sub('', 'blah blah blah'))"
100000 loops, best of 3: 2.2 usec per loop
[matt tmp] python -m timeit "len(''.join('blah blah blah'.split()))"
1000000 loops, best of 3: 0.785 usec per loop
[matt tmp] python -m timeit "len('blah blah blah'.replace(' ', ''))"
1000000 loops, best of 3: 0.437 usec per loop
[matt tmp] python -m timeit "len('blah blah blah') - 'blah blah blah'.count(' ')"
1000000 loops, best of 3: 0.384 usec per loop


这将帮助您确定最快的方法。更多pythonic吗?我会选择最快的,因为性能始终很重要。

关于python - 计算不包含空格的字符数-Python,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25186809/

10-13 02:58