On 2011/11/10 09:10 AM, lina wrote:
Hi,

How to remove the coming duplication,

Here I wrote one (not working):


a=['2', '5', '7', '5', '5']
for i in range(len(a)-1):
        if a[i+1]==a[i]:
                a.remove(a[i+1])
        if i not in range(len(a)):
                break

        
a
['2', '7', '5', '5']

I wish to get a is [2,5,7,5]

just remove the coming duplication, not unique the list.

Thanks for any advice,

Best regards,
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



def remove_coming_duplication(a_list):
return [element for idx, element in enumerate(a_list) if element != a_list[idx-1]]

>>> remove_coming_duplication([2, 5, 7, 5, 5])
[2, 5, 7, 5]
>>> remove_coming_duplication([2, 5, 7, 5, 5, 5, 5, 5, 7, 7, 5])
[2, 5, 7, 5, 7, 5]
>>> remove_coming_duplication(['2', '5', '7', '5', '5'])
['2', '5', '7', '5']

With this you're simply iterating through the list and checking if the current element in the list is not equal to the previous element, and if so it is not a duplicate and will be added to the new list you're creating.

--

Christian Witts
Python Developer

//
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to