"Collapsing" a list into a list of changes

Coates, Steve (ACHE) Steve.Coates at smiths-aerospace.com
Sat Feb 5 03:08:00 EST 2005


It's not _exactly_ what you asked for but it may be enough...

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from sets import Set
>>> l = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
>>> s = Set(l)
>>> s
Set([0, 1, 2, 3, 4, 5])
>>> l2 = list(s)
>>> l2
[0, 1, 2, 3, 4, 5]
>>>

I say it's not exactly what you wanted because I don't think the
ordering
of l2 is necessarily the same as l. That may or may not be a problem for
you.

Regards
Steve



> -----Original Message-----
> From: Alan McIntyre [mailto:alan.mcintyre at esrgtech.com]

> Sent: 04 February 2005 17:44
> To: python-list at python.org
> Subject: "Collapsing" a list into a list of changes
>

> Hi all,
>

> I have a list of items that has contiguous repetitions of

> values, but the number and location of the repetitions is not

> important, so I just need to strip them out.  For example, if

> my original list is [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I

> want to end up with [0,1,2,3,2,4,5].
>

> Here is the way I'm doing this now:
>

> def straightforward_collapse(myList):
>      collapsed = [myList[0]]
>      for n in myList[1:]:
>          if n != collapsed[-1]:
>              collapsed.append(n)
>

>      return collapsed
>

> Is there an elegant way to do this, or should I just stick

> with the code above?
>

> Thanks,
> Alan McIntyre
> http://www.esrgtech.com
>

>


******************************************
The information contained in, or attached to, this e-mail, may contain confidential information and is intended solely for the use of the individual or entity to whom they are addressed and may be subject to legal privilege.  If you have received this e-mail in error you should notify the sender immediately by reply e-mail, delete the message from your system and notify your system manager.  Please do not copy it for any purpose, or disclose its contents to any other person.  The views or opinions presented in this e-mail are solely those of the author and do not necessarily represent those of the company.  The recipient should check this e-mail and any attachments for the presence of viruses.  The company accepts no liability for any damage caused, directly or indirectly, by any virus transmitted in this email.
******************************************



More information about the Python-list mailing list