我怎样才能得到两个日之间的所有的日子吗? [英] How can I get all days between two days?

查看:107
本文介绍了我怎样才能得到两个日之间的所有的日子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要亮了两整天所有的工作日。

例如:

周三 - 周五=周三,周四,周五
        3  -  5 = 3,4,5

 周六 - 周二=周六,周日,周一,周二
        6  -  2 = 6,7,1,2

我是pretty的肯定有一个巧妙的算法,在那里解决这个问题。唯一的算法,我能想到要么使用一个循环或如果语句。

必须有一个优雅的方式来解决这个问题。我用的是数字1-7工作日,但0-6也没关系。

我能想出的最好的:

 高清之间(D1,D2):
     奥尔代斯= [0,1,2,3,4,5,6,0,1,2,3,4,5,6]#或范围(7)* 2
     偏移量= 8如果d1> D2其他1
     返回奥尔代斯[D1:D2 +偏移量]

之间(0,4)
#[0,1,2,3,4]

间(5,2)
#[5,6,0,1,2]
 

解决方案

 >>>高清weekdays_between(S,E):
...回报[n个的范围n%7(S,E +(1如果E> S否则8))]
...
>>> weekdays_between(2,4)
[2,3,4]
>>> weekdays_between(5,1)
[5,6,0,1]
 

这是一个有点复杂,如果你要转换自/至实际天数。

 >>>天='周一周二周三周四周五周六Sun'.split()
>>> days_1 = {D:N对N,D在历数(天)}
>>>高清weekdays_between(S,E):
... S,E = days_1 [S],days_1 [E]
...返回[天[N%7]为N的范围(S,E +(1如果E> S否则8))]
...
>>> weekdays_between('星期三','星期五')
['星期三','周四','周五']
>>> weekdays_between('星期六','星期二')
['星期六','太阳','星期一','星期二']
 

I need all the weekdays between two days.

Example:

Wednesday - Friday  = Wednesday, Thursday, Friday  
        3 - 5       = 3, 4, 5

 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday
        6 - 2       = 6, 7, 1, 2

I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an if statement.

There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.

The best I could come up with:

def between(d1, d2):
     alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6]    # or range(7) * 2
     offset = 8 if d1 > d2 else 1
     return alldays[d1:d2 + offset]

between(0, 4)
# [0,1,2,3,4]

between(5,2)
# [5,6,0,1,2]

解决方案

>>> def weekdays_between(s, e):
...     return [n % 7 for n in range(s, e + (1 if e > s else 8))]
... 
>>> weekdays_between(2, 4)
[2, 3, 4]
>>> weekdays_between(5, 1)
[5, 6, 0, 1]

It's a bit more complex if you have to convert from/to actual days.

>>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split()
>>> days_1 = {d: n for n, d in enumerate(days)}
>>> def weekdays_between(s, e): 
...     s, e = days_1[s], days_1[e]
...     return [days[n % 7] for n in range(s, e + (1 if e > s else 8))]
... 
>>> weekdays_between('Wed', 'Fri')
['Wed', 'Thu', 'Fri']
>>> weekdays_between('Sat', 'Tue')
['Sat', 'Sun', 'Mon', 'Tue']

这篇关于我怎样才能得到两个日之间的所有的日子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆