Return a list of weekdays, starting with given weekday

后端 未结 9 2347
情书的邮戳
情书的邮戳 2021-02-07 23:53

My task is to define a function weekdays(weekday) that returns a list of weekdays, starting with the given weekday. It should work like this:

相关标签:
9条回答
  • 2021-02-08 00:19
    def weekdays(day):
        days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        i=days.index(day) # get the index of the selected day
        d1=days[i:] #get the list from an including this index
        d1.extend(days[:i]) # append the list form the beginning to this index
        return d1
    

    And if you want to test that it works:

    def test_weekdays():
        days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        for day in days:
            print weekdays(day)
    
    0 讨论(0)
  • 2021-02-08 00:21

    Hmm, you are currently only searching for the given weekday and set as result :) You can use the slice ability in python list to do this:

    result = days[days.index(weekday):] + days[:days.index(weekdays)]
    
    0 讨论(0)
  • 2021-02-08 00:24

    You don't need to hardcode array of weekdays. It's already available in calendar module.

    import calendar as cal
    
    def weekdays(weekday):
        start = [d for d in cal.day_name].index(weekday)
        return [cal.day_name[(i+start) % 7] for i in range(7)]
    
    0 讨论(0)
  • 2021-02-08 00:27

    Here's more what you want:

    def weekdays(weekday):
        days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        index = days.index(weekday)
        return (days + days)[index:index+7]
    
    0 讨论(0)
  • 2021-02-08 00:28

    Every time you run the for loop, the day variable changes. So day is equal to your input only once. Using "Sunday" as input, it first checked if Monday = Sunday, then if Tuesday = Sunday, then if Wednesday = Sunday, until it finally found that Sunday = Sunday and returned Sunday.

    0 讨论(0)
  • 2021-02-08 00:33

    Your result variable is a string and not a list object. Also, it only gets updated one time which is when it is equal to the passed weekday argument.

    Here's an implementation:

    import calendar
    
    def weekdays(weekday):
        days = [day for day in calendar.day_name]
        for day in days:
            days.insert(0, days.pop())    # add last day as new first day of list           
            if days[0] == weekday:        # if new first day same as weekday then all done
                break       
        return days
    

    Example output:

    >>> weekdays("Wednesday")
    ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
    >>> weekdays("Friday")
    ['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
    >>> weekdays("Tuesday")
    ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']
    
    0 讨论(0)
提交回复
热议问题