how to remove multiple occurrences of a string within a list?
Ayaz Ahmed Khan
ayaz at dev.slash.null
Thu Apr 5 09:21:19 EDT 2007
"Steven Bethard" typed:
>> Or, just:
>>
>> In [1]: l = ["0024","haha","0024"]
>> In [2]: filter(lambda x: x != "0024", l)
>> Out[2]: ['haha']
>
> Only if you want to make your code harder to read and slower::
Slower, I can see. But harder to read?
> There really isn't much use for filter() anymore. Even in the one place
> I would have expected it to be faster, it's slower::
>
> $ python -m timeit -s "L = ['', 'a', '', 'b']" "filter(None, L)"
> 1000000 loops, best of 3: 0.789 usec per loop
>
> $ python -m timeit -s "L = ['', 'a', '', 'b']" "[i for i in L if i]"
> 1000000 loops, best of 3: 0.739 usec per loop
I am getting varying results on my system on repeated runs. What about
itertools.ifilter()?
$ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools"
"itertools.ifilter(lambda i: i != '1024', L)"
100000 loops, best of 3: 5.37 usec per loop
$ python -m timeit -s "L = ['0024', 'haha', '0024']"
"[i for i in L if i != '0024']"
100000 loops, best of 3: 5.41 usec per loop
$ python -m timeit -s "L = ['0024', 'haha', '0024']" "[i for i in L if i]"
100000 loops, best of 3: 6.71 usec per loop
$ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools"
"itertools.ifilter(None, L)"
100000 loops, best of 3: 4.12 usec per loop
--
Ayaz Ahmed Khan
Do what comes naturally now. Seethe and fume and throw a tantrum.
More information about the Python-list
mailing list