Reputation: 110163
How would I do a > expression in a count? For example:
# equivalence
l = [1,2,2,3,4]
l.count(2)
2
# greater than date
l = [datetime.datetime(2014, 1, 1, 0, 0), datetime.datetime(2015, 1, 1, 0, 0)]
l.count('date is greater than '2014-02-01')
1
Upvotes: 0
Views: 64
Reputation: 123463
Boolean values (and expressions) effectively have a numeric value of 0
or 1
, so you could just add a bunch of them up:
dates = [datetime.datetime(2014, 1, 31, 0, 0),
datetime.datetime(2014, 2, 1, 0, 0),
datetime.datetime(2014, 2, 2, 0, 0)]
cutoff = datetime.datetime(2014, 2, 1, 0, 0)
print(sum(d > cutoff for d in dates)) # --> 1
Upvotes: 0
Reputation: 74655
>>> import datetime
>>> l = [datetime.datetime(2014, 1, 1, 0, 0), datetime.datetime(2015, 1, 1, 0, 0)]
>>> sum(1 for d in l if d > datetime.datetime(2014, 2, 1, 0, 0))
1
For example the expression:
l.count(2)
does the same as:
sum(1 for v in l if v == 2)
But to do what you ask for we need to replace ==
with >
resulting in the solution presented above.
Upvotes: 5