Python 返回工作日列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4082772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:10:07  来源:igfitidea点击:

Return a list of weekdays

python

提问by Gusto

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

我的任务是定义一个weekdays(weekday)返回工作日列表的函数,从工作日开始。它应该像这样工作:

>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

So far I've come up with this one:

到目前为止,我想出了这个:

def weekdays(weekday):
    days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
            'Sunday')
    result = ""
    for day in days:
        if day == weekday:
            result += day
    return result

But this prints the input day only:

但这仅打印输入日期:

>>> weekdays("Sunday")
'Sunday'

What am I doing wrong?

我究竟做错了什么?

采纳答案by toast38coza

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)

回答by user374372

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.

每次运行 for 循环时,day 变量都会改变。所以 day 只等于你的输入一次。使用“Sunday”作为输入,它首先检查是否星期一=星期日,然后检查星期二是否=星期日,然后如果星期三=星期日,直到最终找到星期日=星期日并返回星期日。

回答by tuantub

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:

嗯,您目前只搜索给定的工作日并将其设置为结果:) 您可以使用 python 列表中的切片功能来执行此操作:

result = days[days.index(weekday):] + days[:days.index(weekdays)]

回答by kindall

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]

回答by poke

A far quicker approach would be to keep in mind, that the weekdays cycle. As such, we just need to get the first day we want to include the list, and add the remaining 6 elements to the end. Or in other words, we get the weekday list starting from the starting day, append another full week, and return only the first 7 elements (for the full week).

一个更快的方法是记住,工作日循环。因此,我们只需要获取我们想要包含列表的第一天,并将剩余的 6 个元素添加到最后。或者换句话说,我们从起始日开始获取工作日列表,再追加一个完整的一周,并且只返回前 7 个元素(完整的一周)。

days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
def weekdays ( weekday ):
    index = days.index( weekday )
    return list( days[index:] + days )[:7]

>>> weekdays( 'Wednesday' )
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

回答by Ray

Your resultvariable is a stringand not a listobject. Also, it only gets updated one time which is when it is equal to the passed weekdayargument.

你的result变量是一个string而不是一个list对象。此外,它只会更新一次,也就是当它等于传递的weekday参数时。

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

回答by martineau

The reason your code is only returning one day name is because weekdaywill never match more than one string in the daystuple and therefore won't add any of the days of the week that follow it (nor wrap around to those before it). Even if it did somehow, it would still return them all as one long string because you're initializing resultto an empty string, not an empty list.

您的代码只返回一天名称的原因是因为weekday永远不会匹配days元组中的多个字符串,因此不会添加它后面的一周中的任何一天(也不会环绕到它之前的那些天)。即使它以某种方式做了,它仍然会将它们作为一个长字符串返回,因为您正在初始化result为一个空字符串,而不是一个空的list

Here's a solution that uses the datetimemodule to create a list of all the weekday names starting with "Monday" in the current locale's language. This list is then used to create another list of names in the desired order which is returned. It does the ordering by finding the index of designated day in the original list and then splicing together two slices of it relative to that index to form the result. As an optimization it also caches the locale's day names so if it's ever called again with the same current locale (a likely scenario), it won't need to recreate this private list.

这是一个解决方案,它使用该datetime模块以当前语言环境的语言创建以“星期一”开头的所有工作日名称的列表。然后使用此列表以返回的所需顺序创建另一个名称列表。它通过在原始列表中查找指定日期的索引然后将其相对于该索引的两个切片拼接在一起以形成结果来进行排序。作为优化,它还缓存了语言环境的日期名称,因此如果再次使用相同的当前语言环境(可能的情况)调用它,则不需要重新创建此私有列表。

import datetime
import locale

def weekdays(weekday):
    current_locale = locale.getlocale()
    if current_locale not in weekdays._days_cache:
        # Add day names from a reference date, Monday 2001-Jan-1 to cache.
        weekdays._days_cache[current_locale] = [
            datetime.date(2001, 1, i).strftime('%A') for i in range(1, 8)]
    days = weekdays._days_cache[current_locale]
    index = days.index(weekday)
    return days[index:] + days[:index]

weekdays._days_cache = {}  # initialize cache

print(weekdays('Wednesday'))
# ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

Besides not needing to hard-code days names in the function, another advantage to using the datetimemodule is that code utilizing it will automatically work in other languages. This can be illustrated by changing the locale and then calling the function with a day name in the corresponding language.

除了不需要在函数中硬编码日期名称之外,使用该datetime模块的另一个优点是使用它的代码将自动在其他语言中工作。这可以通过更改区域设置然后使用相应语言的日期名称调用函数来说明。

For example, although France is not my default locale, I can set it to be the current one for testing purposes as shown below. Note: According to this Capitalization of day namesarticle, the names of the days of the week are not capitalized in French like they are in my default English locale, but that is taken into account automatically, too, which means the weekdayname passed to it must be in the language of the current locale and is also case-sensitive. Of course you could modify the function to ignore the lettercase of the input argument, if desired.

例如,虽然法国不是我的默认语言环境,但我可以将其设置为当前语言环境以进行测试,如下所示。注意:根据此日期名称大写文章,星期几的名称不像在我的默认英语语言环境中那样用法语大写,但这也会自动考虑在内,这意味着weekday传递给它的名称必须使用当前语言环境的语言,并且区分大小写。当然,如果需要,您可以修改函数以忽略输入参数的字母。

# set or change locale
locale.setlocale(locale.LC_ALL, 'french_france')

print(weekdays('mercredi'))  # use French equivalent of 'Wednesday'
# ['mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche', 'lundi', 'mardi']

回答by martineau

Another approach using the standard library:

使用标准库的另一种方法:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
        'Sunday']
def weekdays(weekday):
  n = days.index(weekday)
  return list(itertools.islice(itertools.cycle(days), n, n + 7))

Itertools is a bit much in this case. Since you know at most one extra cycle is needed, you could do that manually:

Itertools 在这种情况下有点多。由于您知道最多需要一个额外的周期,因此您可以手动执行此操作:

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
        'Sunday']
days += days
def weekdays(weekday):
  n = days.index(weekday)
  return days[n:n+7]

Both give the expected output:

两者都给出了预期的输出:

>>> weekdays("Wednesday")
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
>>> weekdays("Sunday")
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
>>> weekdays("Monday")
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

回答by Shital Shah

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