はlen(テキスト。split())テキストよりも高速です。カウント("")?そしてなぜそうですか?パイソン
-
21-12-2019 - |
質問
空白で区切られた行ごとに〜20〜100トークンの1,000,000,000行があることを考えると、各行の長さを数えることは一種の非トライバルになります。
2つのトークンの間に二重の空白がないと仮定します,
は
len(text.split())
より速いtext.count(" ")+1
?そしてなぜそうですか?
解決
どちらが速いかを簡単に確認できます:
>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
おそらく分割されたリストを構築するため、遅くなります。
他のヒント
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を取得したくありません。
あなたの前提は間違っています。これらの操作の両方が同じ結果を与えない、例として質問を使用してください。
>>> 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())]
. 所属していません StackOverflow