a_list.count(a_callable) ?
Dustan
DustanGroups at gmail.com
Sat Jun 16 20:28:31 EDT 2007
On Jun 16, 3:37 pm, Dustan <DustanGro... at gmail.com> wrote:
> class SmartCountingList(list):
> def count(self, item, func=lambda x: x):
> return sum(1 for i in self if func(item)==item)
>
> Then, you would call it as follows:
> a_list.count(True, a_function)
I need to learn to think things through before hitting the send button
(or test my examples); none of the mistakes I've made on this thread
have been from ignorance.
If a_function returns a true value other than True or the number 1
(which are technically the same), it is not 'equal' to True. Either
the function would return True, or the count method could be written
differently:
class SmartCountingList(list):
def count(self, item, is_func=False):
if is_func:
# item being a function:
return sum(1 for i in self if item(i))
else:
return super(SmartCountingList, self).count(item)
And just to prove that it works:
>>> s = SmartCountingList((1,2,3))
>>> s
[1, 2, 3]
>>> s.count(1)
1
>>> s.count(2)
1
>>> s.count(3)
1
>>> s.count(4)
0
>>> s.count(lambda n: n<3, True)
2
More information about the Python-list
mailing list