[Tutor] Lists of duplicates

Alan Gauld alan.gauld at yahoo.co.uk
Wed Mar 8 20:03:30 EST 2017


On 08/03/17 19:56, Sri Kavi wrote:

> It’s about making a function that returns a list of lists, with each list
> being all of the elements that are the same as another element in the
> original list.

This is one of those problems where there is probably no
definitive "correct" answer just different compromises.

My first reaction was to sort the initial list then iterate
over it creating a new sublist for each change of value.
But, it only works for homogenous lists. For mixed types
I'd probably opt for a dictionary:

def f(lst):
    res = {}
    for item in lst:
	res.setdefault(item,[]).append(item)
    return list(res.values())

But I've no idea how that performs compared to your methods.

> def sublist_duplicates(lst):
>     sublists = []
> 
>     for item in set(lst):
>         sublists.append([item] * lst.count(item))
> 
>     return sublists



> def sublist_duplicates(lst):
>     counts = Counter(lst)
>     sublists = [[k] * counts[k] for k in counts]
>     return sublists

> I found that the first version works better with a small list, but the
> second version outperforms the first one when it’s given a considerably big
> list of data.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list