Array delete
Steven Bethard
steven.bethard at gmail.com
Wed Feb 7 19:27:29 EST 2007
Jerry Hill wrote:
> On 1/28/07, Scripter47 <nospam at riddergarn.dk> wrote:
>> Can someone plz make a function for that takes a array, and then search
>> in it for duplicates, if it finds 2 or more items thats the same string
>> then delete all except 1.
>
> >>> myList = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10]
> >>> myList = list(set(myList))
> >>> print myList
> [8, 1, 2, 4, 10]
>
> Maintaining sort order is left as an exercise for the reader.
A "simple" two-liner that maintains order:
>>> items = [1, 1, 2, 4, 8, 8, 8, 8, 8, 8, 10]
>>> seen = set()
>>> [x for x in items if x not in seen and not seen.add(x)]
[1, 2, 4, 8, 10]
Mmm... what a beautiful abuse of "and". ;-)
STeVe
More information about the Python-list
mailing list