假设我有一个下雨日期的日期列表。
rained=["01-05-2012","05-01-2012","01-12-2012","06-14-2013"]
日期的顺序是月,日,年。从列表中可以看出,在这些日期中,一月份(01)下雨最多。我怎样才能为此创建代码?
答案 0 :(得分:4)
使用collections.Counter
:
>>> rained=["01-05-2012","05-01-2012","01-12-2012","06-14-2013"]
>>> from collections import Counter
>>> Counter(x[:2] for x in rained).most_common()[0][0]
'01'
most_common()
将按降序返回项目元组列表和计数:
>>> Counter(x[:2] for x in rained).most_common()
[('01', 2), ('06', 1), ('05', 1)]
答案 1 :(得分:0)
使用split()函数按符号' - '拆分列表中的每个项目,然后分析您可以得到答案的月份。
答案 2 :(得分:0)
如果有平局,你可以做这样的事情
>>> rained=["01-05-2012", "05-01-2012", "01-12-2012", "06-14-2013"]
>>> from collections import Counter
>>> counts = Counter(x[:2] for x in rained).most_common()
>>> [i for i, j in counts if j==counts[0][1]]
['01']
这是一个带有平局的例子
>>> rained=["01-05-2012", "05-01-2012", "01-12-2012", "06-14-2013", "06-12-2013"]
>>> counts = Counter(x[:2] for x in rained).most_common()
>>> [i for i, j in counts if j==counts[0][1]]
['01', '06']