Мне было любопытно посмотреть на эффективность различных подходов и доказать, что понимание не очень хорошо каждый раз, когда я проводил некоторый анализ с использованием словарного понимания, словарного преобразования путем преобразования входных данных в наборы и традиционные для циклов. Имеет смысл, почему понимание здесь дорого, поскольку .count()
повторяется по всему text
каждый раз, чтобы подсчитать частоту одиночного char
from timeit import timeit
print('Approach 1 without set compehrension: {}'.format(timeit ('{ch: text.count(ch) for ch in text}',setup='text = "asampletextstring"',number=1000000)))
print('Approach 2 with set compehrension: {}'.format(timeit ('{ch: text.count(ch) for ch in set(text)}',setup='text = "asampletextstring"',number=1000000)))
print('Approach 3 simple loops :{}'.format(timeit('for c in text:char_count[c] = char_count.get(c, 0) + 1',setup='text = "asampletextstring";char_count={};',number=1000000)))
print('Approach 4 Counter :{}'.format(timeit('Counter(text)',setup='text = "asampletextstring";from collections import Counter;',number=1000000)))
Выход:
Approach 1 without set compehrension: 4.43441867505
Approach 2 with set compehrension: 3.98101747791
Approach 3 simple loops :2.60219633984
Approach 4 Counter :7.54261124884