我怎样才能在两天之间得到所有的日子?

我需要两天之间的所有工作日。

例:

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

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

我很确定有一个聪明的算法来解决这个问题。 我能想到的唯一算法使用循环或if语句。

必须有一个优雅的方式来解决这个问题。 我在平日使用数字1-7,但0-6也很好。

我能想到的最好的:

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]

如果您必须将日期转换为实际日期,则会更复杂一些。

>>> 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']

如何(在伪代码中):

weekday[] = {"Mon" .. "Sun"}
for(i = wkday_start; (i % 7) != wkday_end; i = (i+1) % 7)
    printf("%s ", weekday[i]);

它的工作方式类似于循环缓冲区,wkday_start是从(0开始)开始的索引,wkday_end是结束索引。

希望这可以帮助

乔治。


基于Stephan202的出色答案,您可以概括圆形切片的概念。

>>> def circular_slice(r, s, e):
... return [r[n % len(r)] for n in range(s, e + (1 if e>s else len(r)+1))]
...
>>> circular_slice(range(0,7), 2, 4)
[2, 3, 4]
>>> circular_slice(range(0,7), 5, 1)
[5, 6, 0, 1]
>>> circular_slice('Mon Tue Wed Thu Fri Sat Sun'.split(), 5, 1)
['Sat', 'Sun', 'Mon', 'Tue']
链接地址: http://www.djcxy.com/p/54881.html

上一篇: How can I get all days between two days?

下一篇: AddBusinessDays and GetBusinessDays