David542
David542

Reputation: 110163

Count by > DATE

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

Answers (2)

martineau
martineau

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

Dan D.
Dan D.

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

Related Questions