[Tutor] sorting into lists

Don Arnold darnold02@sprynet.com
Fri, 20 Sep 2002 22:59:15 -0500


I'm sure there are slicker ways to do what you want, but this works:

origList = [1,1,1,2,2,3,3,3,3,4,4]
finalList = []
currList = []

lastItem = origList[0]
for item in origList:
    if item == lastItem:
        currList.append(item)
    else:
        finalList.append(currList)
        lastItem = item
        currList = [item]

finalList.append(currList)

print 'original list:', origList
print 'final list:   ', finalList

>>> 
original list: [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4]
final list:    [[1, 1, 1], [2, 2], [3, 3, 3, 3], [4, 4]]


Don

----- Original Message ----- 
From: "Tim Wilson" <wilson@visi.com>
To: <tutor@python.org>
Sent: Friday, September 20, 2002 10:37 PM
Subject: [Tutor] sorting into lists


> Hey everyone,
> 
> Let's say I've got a list like the following:
> 
> l = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4]
> 
> I'm trying to figure out a good way to turn this list into
> 
> [[1, 1, 1], [2, 2], [3, 3, 3, 3], [4, 4]]
> 
> Any ideas?
> 
> -Tim
> 
> -- 
> Tim Wilson      |   Visit Sibley online:   | Check out:
> Henry Sibley HS |  http://www.isd197.org   | http://www.zope.com
> W. St. Paul, MN |                          | http://slashdot.org
> wilson@visi.com |  <dtml-var pithy_quote>  | http://linux.com
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor