[Tutor] Lists of duplicates
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Mar 9 04:04:28 EST 2017
On 09/03/17 04:29, Alex Kleider wrote:
>> I'd probably opt for a dictionary:
>>
>> def f(lst):
>> res = {}
>> for item in lst:
>> res.setdefault(item,[]).append(item)
>> return list(res.values())
>>
> The above works BUT
> how????
setdefault returns the current value for the key
or the default, in this case an empty list.
So we can split it in two as:
for item in lst:
val = res.setdefault(item,[])
val.append(item)
And since setdefault also assigns the default
to the dict if it doesn't exist we don't need
to add an extra assignment.
We could have used get() instead:
for item in lst:
sub = res.get(item,[])
sub.append(item)
res[item] = sub
Is that any clearer?
Breaking setdefault() down gives something like:
try:
sub = res[item]
except KeyError:
res[item] = []
sub = res[item]
--
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