多条件排序问题:
# 样例输入
input: [2, 3, 3, 4, 1, 1, 1, 6, 6, 4, 7, 8, 55, 4]
# 需求:按元素的出现次数降序排列,出现次数相同的元素按值降序排列
# 样例输出
output: [4, 4, 4, 1, 1, 1, 6, 6, 3, 3, 55, 8, 7, 2]
Solution:
>>> from collections import Counter
>>> input = [2, 3, 3, 4, 1, 1, 1, 6, 6, 4, 7, 8, 55, 4]
>>> output = []
>>> c = Counter(input)
>>> c
Counter({1: 3, 4: 3, 3: 2, 6: 2, 2: 1, 7: 1, 8: 1, 55: 1})
>>> m = c.most_common() # 按出现次数降序排列
>>> m
[(1, 3), (4, 3), (3, 2), (6, 2), (2, 1), (7, 1), (8, 1), (55, 1)]
>>> s = sorted(m, key=lambda x: (x[1], x[0]), reverse=True) # 匿名函数返回一个元组,按照元组内元素的顺序排序
>>> s
[(4, 3), (1, 3), (6, 2), (3, 2), (55, 1), (8, 1), (7, 1), (2, 1)]
>>> for v, c in s:
... output += [v] * c
...
>>> output
[4, 4, 4, 1, 1, 1, 6, 6, 3, 3, 55, 8, 7, 2]
获取两个日期之间的所有日期:
# 样例输入(两个日期的年份不一定相同)
input: start=2017/7/11 end=2017/7/16
# 需求:返回两个日期之间所有日期的列表
# 样例输出
output: [2017/7/11, 2017/7/12, 2017/7/13, 2017/7/14, 2017/7/15, 2017/7/16]
Solution:
from datetime import datetime, timedelta
def get_date_list(start, end):
date_list = []
start = datetime.strptime(start, '%Y/%m/%d')
end = datetime.strptime(end, '%Y/%m/%d')
if start > end:
return []
else:
day_range = (end - start).days # 两个日期相差的天数,即输出的日期范围
for d in xrange(day_range):
date_list.append(start + timedelta(days=1) * d ) # 开始日期逐个加 1 days 得到所有日期
date_list.append(end) # 上面得到的日期列表不包含end日期
return date_list