Python: 将 ('Monday', 'Tuesday', 'Wednesday') 转换为 'Monday to Wednesday

6 投票
7 回答
6947 浏览
提问于 2025-04-16 08:44

我想得到一系列的星期几。下面是我想做的Python代码:

def week_days_to_string(week_days):
    """
    >>> week_days_to_string(('Sunday', 'Monday', 'Tuesday'))
    'Sunday to Tuesday'
    >>> week_days_to_string(('Monday', 'Wednesday'))
    'Monday and Wednesday'
    >>> week_days_to_string(('Sunday', 'Wednesday', 'Thursday'))
    'Sunday, Wednesday, Thursday'
    """
    if len(week_days) == 2:
       return '%s and %s' % weekdays
    elif week_days_consecutive(week_days):
       return '%s to %s' % (week_days[0], week_days[-1])
    return ', '.join(week_days)

我只需要week_days_consecutive这个函数(这部分比较难,嘿嘿)。

有没有什么想法可以帮我实现这个?

说明:

我之前的表述和例子让人有些困惑。我并不想把这个函数限制在工作日。我想考虑一周的所有天(星期日、星期一、星期二、星期三、星期四、星期五)。抱歉昨晚没有说清楚。我已经修改了问题的内容以便更清楚。

编辑:增加了一些复杂性

循环序列:

>>> week_days_to_string(('Sunday', 'Monday', 'Tuesday', 'Saturday'))
'Saturday to Tuesday'

而且,根据@user470379的建议,这是可选的:

>>> week_days_to_string(('Monday, 'Wednesday', 'Thursday', 'Friday'))
'Monday, Wednesday to Friday'

7 个回答

1

这是我完整的解决方案,你可以随意使用;(这段代码是公开的,我不对你或你的电脑使用它后发生的任何事情负责,也没有任何保证等等)。

week_days = {
    'monday':0,
    'tuesday':1,
    'wednesday':2,
    'thursday':3,
    'friday':4,
    'saturday':5,
    'sunday':6
}
week_days_reverse = dict(zip(week_days.values(), week_days.keys()))

def days_str_to_int(days):
    '''
    Converts a list of days into a list of day numbers.
    It is case ignorant.
    ['Monday', 'tuesday'] -> [0, 1]
    '''
    return map(lambda day: week_days[day.lower()], days)

def day_int_to_str(day):
    '''
    Converts a day number into a string.
    0 -> 'Monday' etc
    '''
    return week_days_reverse[day].capitalize()

def consecutive(days):
    '''
    Returns the number of consecutive days after the first given a sequence of 
    day numbers.
    [0, 1, 2, 5] -> 2
    [6, 0, 1] -> 2
    '''
    j = days[0]
    n = 0
    for i in days[1:]:
        j = (j + 1) % 7
        if j != i:
            break
        n += 1
    return n

def days_to_ranges(days):
    '''
    Turns a sequence of day numbers into a list of ranges.
    The days can be in any order
    (n, m) means n to m
    (n,) means just n
    [0, 1, 2] -> [(0, 2)]
    [0, 1, 2, 4, 6] -> [(0, 2), (4,), (6,)] 
    '''
    days = sorted(set(days))
    while days:
        n = consecutive(days)
        if n == 0:
            yield (days[0],)
        else:
            assert n < 7
            yield days[0], days[n]
        days = days[n+1:]

def wrap_ranges(ranges):
    '''
    Given a list of ranges in sequential order, this function will modify it in 
    place if the first and last range can be put together.
    [(0, 3), (4,), (6,)] -> [(6, 3), (4,)]
    '''
    if len(ranges) > 1:
        if ranges[0][0] == 0 and ranges[-1][-1] == 6:
            ranges[0] = ranges[-1][0], ranges[0][-1]
            del ranges[-1]

def range_to_str(r):
    '''
    Converts a single range into a string.
    (0, 2) -> "Monday to Wednesday"
    '''
    if len(r) == 1:
        return day_int_to_str(r[0])
    if r[1] == (r[0] + 1) % 7:
        return day_int_to_str(r[0]) + ', ' + day_int_to_str(r[1])
    return day_int_to_str(r[0]) + ' to ' + day_int_to_str(r[1])

def ranges_to_str(ranges):
    '''
    Converts a list of ranges into a string.
    [(0, 2), (4, 5)] -> "Monday to Wednesday, Friday, Saturday"
    '''
    if len(ranges) == 1 and ranges[0] == (0, 6):
        return 'all week'
    return ', '.join(map(range_to_str, ranges))

def week_days_to_string(days):
    '''
    Converts a list of days in string form to a stringed list of ranges.
    ['saturday', 'monday', 'wednesday', 'friday', 'sunday'] -> 
        'Friday to Monday, Wednesday'
    '''
    ranges = list(days_to_ranges(days_str_to_int(days)))
    wrap_ranges(ranges)
    return ranges_to_str(ranges)

功能:

  • 它支持多个范围,
  • 你可以随意输入日期,顺序没关系,
  • 它会自动循环,

如果你发现任何问题,请留言,我会尽力修复它们。

2
def weekdays_consecutive(inp):
    days = { 'Monday': 0,
             'Tuesday': 1,
             'Wednesday': 2,
             'Thursday': 3,
             'Friday': 4 }

    return [days[x] for x in inp] == range(days[inp[0]], days[inp[-1]] + 1)

既然你已经检查过其他情况了,我觉得这样就足够了。

5

我会这样来解决这个问题:

  • 先创建一个字典,把每个星期几的名字和它们的顺序编号对应起来
  • 把我输入的星期几的名字转换成它们的顺序编号
  • 查看这些编号,看看它们是否是连续的

下面是如何做到这一点,使用了 calendar.day_namerange 和一些简单的循环:

day_indexes = {name:i for i, name in enumerate(calendar.day_name)}
def weekdays_consecutive(days):
    indexes = [day_indexes[d] for d in days]
    expected = range(indexes[0], indexes[-1] + 1)
    return indexes == expected

还有一些其他的选择,具体取决于你的需求:

  • 如果你需要使用 Python 版本低于 2.7,可以用下面的方式代替字典推导:

    day_indexes = dict((name, i) for i, name in enumerate(calendar.day_name))
    
  • 如果你不想包括星期六和星期天,可以把最后两天去掉:

    day_indexes = ... calendar.day_name[:-2] ...
    
  • 如果你需要在星期天之后循环,可以检查每个项是否比前一个项大 1,但要用 7 取余:

    def weekdays_consecutive(days):
        indexes = [day_indexes[d] for d in days]
        return all(indexes[i + 1] % 7 == (indexes[i] + 1) % 7
                   for i in range(len(indexes) - 1))
    

更新:对于扩展的问题,我还是会使用星期几到编号的字典,但我会:

  • 找出连续的星期几在哪些地方停止
  • 如果需要,把星期几循环起来,以获得最长的连续天数
  • 把这些天分组,形成它们的连续范围

下面是实现这个功能的代码:

def weekdays_to_string(days):
    # convert days to indexes
    day_indexes = {name:i for i, name in enumerate(calendar.day_name)}
    indexes = [day_indexes[d] for d in days]

    # find the places where sequential days end
    ends = [i + 1
            for i in range(len(indexes))
            if (indexes[(i + 1) % len(indexes)]) % 7 !=
               (indexes[(i) % len(indexes)] + 1) % 7]

    # wrap the days if necessary to get longest possible sequences
    split = ends[-1]
    if split != len(days):
        days = days[split:] + days[:split]
        ends = [len(days) - split + end for end in ends]

    # group the days in sequential spans
    spans = [days[begin:end] for begin, end in zip([0] + ends, ends)]

    # format as requested, with "to", "and", commas, etc.
    words = []
    for span in spans:
        if len(span) < 3:
            words.extend(span)
        else:
            words.append("%s to %s" % (span[0], span[-1]))
    if len(days) == 1:
        return words[0]
    elif len(days) == 2:
        return "%s and %s" % tuple(words)
    else:
        return ", ".join(words)

你也可以尝试用下面的方式替代最后的 if/elif/else 代码块,这样可以在最后两个项之间加上“和”,其他项之间加上逗号:

    if len(words) == 1:
        return words[0]
    else:
        return "%s and %s" % (", ".join(words[:-1]), words[-1])

这和最初的要求有点不同,但在我看来更美观。

撰写回答