[英]python basics - I am trying to write a function which takes a string(a month) as an input and returns the amount of days in the month
I am trying to write a function which takes a string(a month) as an input and returns the amount of days in the month, using a list like this below:我正在尝试编写一个 function,它将一个字符串(一个月)作为输入并返回该月的天数,使用如下列表:
I put in the correction at the bottom, thanks for the help我把更正放在底部,谢谢你的帮助
month_days= [('January',[31]),('February',[28,29]),('March',[31]), ('April',[30]),('May',[31]),('June',[30]),('July',[31]),('August',[31]),('September',[30]),('October',[31]),
('November',[30]),('December',[31]) ]
def month_day(mnth):
for m, d in month_days:
if m == mnth:
return d
This seems like it may be a homework assignment, but if it's not you can use the monthrange
function in the calendar
module (as described in this SO question ):这似乎是一项家庭作业,但如果不是,您可以在calendar
模块中使用monthrange
(如本 SO 问题中所述):
>>> months = ['January','February','March','April','May','June', 'July','August','September','October','November','December']
>>> from calendar import monthrange
>>> for i in range(len(months)):
... ind = i+1
... print months[i], monthrange(2012,ind)[1] # returns a tuple, second element is number of days
...
January 31
February 29
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31
You may want to define the year dynamically since that determines whether it's a leap year or not, but otherwise this seems to give the data you want.您可能想要动态定义年份,因为它决定了它是否是闰年,但除此之外,这似乎可以提供您想要的数据。
Don't invent a bike.不要发明自行车。 Just use the calendar module http://docs.python.org/library/calendar.html只需使用日历模块http://docs.python.org/library/calendar.html
Here's a very basic way of traversing the list, finding the right month and returning the number of days.这是遍历列表、找到正确的月份并返回天数的一种非常基本的方法。 This is not a complete or optimal solution, just an example so you can build up on it.这不是一个完整的或最佳的解决方案,只是一个示例,您可以在此基础上进行构建。
month_days_list = [('January',[31]),('February',[28,29]),('March',[31]), ... ]
def month_days(month):
for m, d in month_days_list:
if m == month:
return d[0]
You should do something about the months that have more than one option of days, instead of just returning d[0].你应该对有多个天选项的月份做一些事情,而不是仅仅返回 d[0]。
FYI in general the simplest way to solve this type of problem (given a string print a constant) is with a dictionary:仅供参考,通常解决此类问题的最简单方法(给定字符串打印常量)是使用字典:
month2days = { 'January': 31, 'February': 29, } ## and so on
print (month2days['January'])
will print 31将打印 31
Using a list of tuples is not the best way.使用元组列表不是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.