from collections import Counter
import random
import timeit
data = [random.randint(0, 9) for _ in range(1000)]
def ex1():
c = Counter(data)
return [i for i in data if c[i] > 1]
def ex2():
return [i for i in data if data.count(i) > 1]
if __name__ == '__main__':
print('ex1', timeit.timeit(ex1, number=1000))
print('ex2', timeit.timeit(ex2, number=1000))
('ex1', 0.3047502040863037)
('ex2', 7.602175951004028)
from collections import Counter
import random
import timeit
data = [random.randint(0, 9) for _ in range(1000)]
def ex1():
return [k for k, v in Counter(data).items() if v > 1]
def ex2():
return [i for i in data if data.count(i) > 1]
if __name__ == '__main__':
print('ex1', timeit.timeit(ex1, number=1000))
print('ex2', timeit.timeit(ex2, number=1000))
>>> ('ex1', 0.26424193382263184)
>>> ('ex2', 7.536624908447266)
Многие со мной не согласятся. Просто они идут другим путем.