Can I overload the compare (cmp()) function for a Lists ([]) index function?
Steven Bethard
steven.bethard at gmail.com
Fri Sep 28 19:42:49 EDT 2007
irstas at gmail.com wrote:
> On Sep 28, 8:30 pm, xkenneth <xkenn... at gmail.com> wrote:
>> Looking to do something similair. I'm working with alot of timestamps
>> and if they're within a couple seconds I need them to be indexed and
>> removed from a list.
>> Is there any possible way to index with a custom cmp() function?
>>
>> I assume it would be something like...
>>
>> list.index(something,mycmp)
>>
>> Thanks!
>
> Wouldn't it be enough to get the items that are "within a couple of
> seconds" out of the list and into another list. Then you can process
> the other list however you want. Like this:
>
> def isNew(x):
> return x < 5
>
> data = range(20)
> print data
> out, data = filter(isNew, data), filter(lambda x: not isNew(x), data)
> print out, data
Slightly off topic here, but these uses of filter will be slower than
the list comprehension equivalents::
out = [x for x in data if x < 5]
data = [x for x in data if x >= 5]
Here are sample timings::
$ python -m timeit -s "data = range(20)" -s "def is_new(x): return x <
5" "filter(is_new, data)"
100000 loops, best of 3: 5.05 usec per loop
$ python -m timeit -s "data = range(20)" "[x for x in data if x < 5]"
100000 loops, best of 3: 2.15 usec per loop
Functions like filter() and map() are really only more efficient when
you have an existing C-coded function, like ``map(str, items)``. Of
course, if the filter() code is clearer to you, feel free to use it, but
I find that most folks find list comprehensions easier to read than
map() and filter() code.
STeVe
More information about the Python-list
mailing list