[Tutor] Flatten a list in tuples and remove doubles

Peter Otten __peter__ at web.de
Sun Jul 29 13:21:10 CEST 2012


Mark Lawrence wrote:

> On 29/07/2012 00:53, Alan Gauld wrote:
>> On 29/07/12 00:12, Francesco Loffredo wrote:
>>
>>> Every time this happens, I have to admit that I'm a newbie and I've
>>> still got a lot to learn about Python. Especially about its wonderful
>>> standard library.
>>
>> Don't worry, I've been using Python for 15 years and there are
>> plenty modules I haven't explored yet - and I must admit itertools
>> is one that I really should get to grips with but never seem to
>> find the time!
>>
> 
> You're nuts :)  Itertools to me is the Swiss Army Knife of the standard
> library, I've used it umpteen times.  Even the recipes are on PyPi.  The
> investment of a little time studying it will easily be repaid in the
> long term.

If you don't have to deal with large datasets many of its functions can 
easily be emulated with lists and loops though. As an example here's the 
grouping with a plain vanilla dict:

groups = {}
for item in data:
    groups.setdefault(item[:4], []).append(item[-2:])

result = [key + tuple("{}/{}".format(*v) for v in values) for key, values in 
groups.items()]




More information about the Tutor mailing list