len(text.split())比text.count(“”)更快吗?为什么呢?蟒蛇

时间:2014-02-26 09:23:41

标签: python string count text-files string-length

鉴于每行由空格分隔的行数为1,000,000,000行~20-100个令牌,计算每行的长度就变成了非繁琐的行。

假设两个令牌之间从不存在双重空格,

  1. len(text.split())text.count(" ")+1更快吗?

  2. 为什么会这样?

3 个答案:

答案 0 :(得分:3)

易于检查哪个更快:

>python -m timeit -s "s='q w e r t y u i o p a s d f g h j k l'" "s.count(' ')+1"
1000000 loops, best of 3: 0.272 usec per loop

>python -m timeit -s "s='q w e r t y u i o p a s d f g h j k l'" "len(s.split())"
1000000 loops, best of 3: 0.653 usec per loop

split速度较慢,可能是因为它构造了拆分列表。

答案 1 :(得分:2)

text.count(" ")错误,请参阅以下内容:

In [706]: t='a  b    c'

In [707]: t.split()
Out[707]: ['a', 'b', 'c']

In [708]: t.count(' ')
Out[708]: 6

在这种情况下你不想得到6。

答案 2 :(得分:2)

你的前提是不正确的。这两个操作都没有给出相同的结果,让我们以你的问题为例:

>>> text = "Given that I have 1,000,000,000 lines of ~20-100 tokens per line delimited by whitespace, counting the length of each line becomes sort of non-trival."
>>> len(text.split())
24
>>> text.count(" ")
23

考虑到你的“计算每条线的长度”的问题,这些操作都不会这样做。

要计算您需要执行的每一行:

line_lengths = [len(line) for line in text.splitlines()]

但最好还是注意行号:

line_lengths = [(idx, len(line)) for idx, line in enumerate(text.splitlines())]
相关问题