2015-03-02 122 views
0

如何在計數中進行表達?例如:按日期計算>日期

# 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 

回答

5
>>> 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 

例如表達:

l.count(2) 

不一樣:

sum(1 for v in l if v == 2) 

但要做到你要求什麼,我們需要更換==導致上述解決方案。

0

布爾值(和表達式)具有有效的01數值,所以你可以只添加了一堆人了:

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