[Tutor] Clubbing simillar elements together in a list with repeating elements

ranjan das ranjand2005 at gmail.com
Thu Feb 24 12:29:27 CET 2011


I have a list

a=[1,2,3,4,2,5,5,4,6,7,8]

I want to club the repeating elements together and my output should be
something like

a_new=[ [1], [2,2], [3], [4,4] , [5,5,5],[6], [7], [8]]

How do I do this?

I tried the following but it is not giving me the desired result


a=[1,2,3,2,3,4,5,4,5,5,6]

Output=[]
Unique=[]
Duplicate=[]

FinList=[]


for element in a:
    if element not in Unique:
        Unique.append(element)
    else:
        Duplicate.append(element)



for element in Unique:

    if element in Duplicate:

        count=0

        for i in Duplicate:
            if i==element:
                count=count+1


        for j in range(count+1):
            FinList.append(element)

    else:

        FinList.append([element])



print Unique

print Duplicate

print FinList

*result:*

Unique=[1, 2, 3, 4, 5, 6]
Duplicate=[2, 3, 4, 5, 5]

FinList=[[1], 2, 2, 3, 3, 4, 4, 5, 5, 5, [6]]

I want the FinList as [ [1], [2,2], [3,3], [4,4] , [5,5,5],[6]]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110224/ad6d72de/attachment.html>


More information about the Tutor mailing list