我该如何做>计算中的表达?例如:
# 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
答案 0 :(得分: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)
但要按照您的要求执行操作,我们需要将==
替换为>
,从而产生上述解决方案。
答案 1 :(得分:0)
布尔值(和表达式)有效地具有0
或1
的数值,因此您可以添加一堆它们:
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