"Collapsing" a list into a list of changes

Peter Otten __peter__ at web.de
Mon Feb 7 02:24:13 EST 2005


Francis Girard wrote:

> This is a prefect use case for the good old "reduce" function:
> 
> --BEGIN SNAP
> 
> a_lst = [None,0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
> 
> def straightforward_collapse(lst):
> return reduce(lambda v,e: v[-1]!=e and v+[e] or v, lst[1:], [lst[0]])
 
reduce() magically increases the number of function calls by len(a_list).
There will be no good use cases for reduce() until Python can inline
functions.

Apodictically Yours
Peter




More information about the Python-list mailing list