[Tutor] Lists of duplicates

Steven D'Aprano steve at pearwood.info
Thu Mar 9 09:20:00 EST 2017


On Wed, Mar 08, 2017 at 08:29:19PM -0800, Alex Kleider wrote:

> The algorithm I came up with is:
> def make_sublists_of_duplicates(original_list):
>     frequency_counter = {}
>     for item in original_list:
>         _ = frequency_counter.setdefault(item, 0)
>         frequency_counter[item] += 1
>     res = []
>     for key in frequency_counter:
>         res.append([key for i in range(frequency_counter[key])])
>     return res
> 
> although I would argue that the creation of the frequency_counter should 
> be in its own function 

Indeed it should, and that function already exists. It is called 
collections.Counter.

from collections import Counter
frequencies = Counter(original_list)


-- 
Steve


More information about the Tutor mailing list