Python:如何从日期列表计算日期范围?
我有一个日期列表,例如:
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08']
如何查找这些日期中包含的连续日期范围?在上面的例子中,范围应该是:
[{"start_date": '2011-02-27', "end_date": '2011-03-01'},
{"start_date": '2011-04-12', "end_date": '2011-04-13'},
{"start_date": '2011-06-08', "end_date": '2011-06-08'}
]
谢谢。
I have a list of dates, for example:
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08']
How do I find the contiguous date ranges contained within those dates? In the above example, the ranges should be:
[{"start_date": '2011-02-27', "end_date": '2011-03-01'},
{"start_date": '2011-04-12', "end_date": '2011-04-13'},
{"start_date": '2011-06-08', "end_date": '2011-06-08'}
]
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个替代解决方案:它返回一个(开始,完成)的列表元组,因为这就是我所需要的;)。
这会改变列表,所以我需要复制一份。显然,这会增加内存使用量。我怀疑 list.pop() 不是超级高效,但这可能取决于 python 中 list 的实现。
您可以轻松更改附加行以附加字典,或使用yield而不是附加到列表。
哦,我的假设他们已经是约会对象了。
Here is an alternative solution: It returns a list tuples of (start,finish), as that's what I needed ;).
This mutates the list, so I needed to make a copy. Obviously, that increases the memory usage. I suspect that list.pop() is not super-efficient, but that probably depends on the implementation of list in python.
You could easily change the append line to append a dict, or yield instead of appending to a list.
Oh, and mine assumes they are already dates.
这可行,
但我对此不满意,将研究更清晰的解决方案并编辑答案。完成,这是一个干净、有效的解决方案:以及相对输出:
This works,
but I'm not happy with it, will work on a cleaner solution an edit the answer. Done, here is a clean, working solution:And the relative output:
尝试忍者 GaretJax 的编辑:;)
Attempting to ninja GaretJax's edit: ;)
结果如下:
slices
列表理解获取前一个日期不是当前日期前一天的所有索引。在前面添加0
,在末尾添加len(dates)
,每个日期范围可以描述为dates[slices[i]:slices[i+ 1]-1]
。Results in the following:
The
slices
list comprehension gets all indices at which the previous date is not one day before the current date. Add0
to the front andlen(dates)
to the end and each range of dates can be described asdates[slices[i]:slices[i+1]-1]
.我对主题略有不同(我最初构建了开始/结束列表并将它们压缩以返回元组,但我更喜欢@Karl Knechtel 的生成器方法):
以下是测试用例:
打印:
My slight variation on the theme (I originally built start/end lists and zipped them to return tuples, but I preferred @Karl Knechtel's generator approach):
Here are the test cases:
Prints: