On Jan 18, 3:06 am, Peter Otten <[email protected]> wrote:
> samwyse wrote:
> > Lately, I've slinging around a lot of lists, and there are some simple
> > things I'd like to do that just aren't there.
>
> > s.count(x[, cmp[, key]])
> > - return number of i‘s for which s[i] == x. 'cmp' specifies a custom
> > comparison function of two arguments, as in '.sort'. 'key' specifies
> > a custom key extraction function of one argument.
>
> What's your use case exactly? If I were to enhance count/index/rindex I
> would go for the simpler
>
> >>> missing = object()
> >>> class List(list):
>
> ... def count(self, value=missing, predicate=missing):
> ... if value is missing:
> ... if predicate is missing:
> ... raise TypeError
> ... return sum(1 for item in self if predicate(item))
> ... else:
> ... if predicate is not missing:
> ... raise TypeError
> ... return list.count(self, value)
> ...>>> items = List(range(10))
> >>> items.count(7)
> 1
> >>> items.count(predicate=lambda item: item%3)
>
> 6
>
> which nicely covers all applications I can imagine.
>
> Peter
That is a good idea. However, I was looking more at the simplicity of
building of ideas that are already present in .sort. And this
implementation is pretty simple as well.
>>> class List(list):
import __builtin__
def count(self, value, cmp=__builtin__.cmp):
return sum(1 for item in self if not cmp(item, value))
>>> items = List(range(10))
>>> items.count(7)
1
>>> items.count(3, lambda a, b: not a%b) # My way
6
>>> items.count(Ellipsis, lambda a, b: not a%3) # Your way
6
As a side note, wouldn't it be nice if '...' could be used in more
places than just slices? IMHO, a useful idiom would be to use it to
signify "irrelevant" or "don't care", as opposed to 'None' which (in
my mind, at least) signifies "missing" or "unknown".
--
http://mail.python.org/mailman/listinfo/python-list