我需要撰寫一個名為的函式,該函式day_of_the_year需要一個月和一天作為輸入,并回傳一年中的相關日期。用一個從 1(代表一月)到 12(代表十二月)的數字來表示月份。例如:
day_of_the_year(1, 1) = 1
day_of_the_year(2, 1) = 32
day_of_the_year(3, 1) = 60
使用回圈將您感興趣的月份之前所有月份的完整天數相加,然后將剩余的天數相加。例如,要查找 3 月 5 日是一年中的哪一天,請將 days_per_month 中的前兩個條目相加以獲得 1 月和 2 月的總天數,然后再相加 5 天。
到目前為止,我已經列出了一個清單:
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
到目前為止,這是我的代碼:
def day_of_the_year(month,day):
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for number in day_of_the_year:
total = days_per_month[0] days_per_month[1] 5
return total
有什么我想念的嗎?
uj5u.com熱心網友回復:
是的,您每次都在第一次通過時退出回圈。
您應該做的是total在 for 回圈之外定義變數,然后在每次迭代時遞增它。
您還只需要迭代到指定的月份,因此使用 range 函式進行回圈。并且由于是函式的名稱,如果您嘗試將其放入回圈day_of_the_year中,則會導致錯誤。for
然后,一旦回圈完成,您可以將天數添加到總計并回傳。
def day_of_the_year(month,day):
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
total = 0
for number in range(month - 1):
total = days_per_month[number]
return total day
print(day_of_the_year(1,1))
print(day_of_the_year(12,25))
輸出:
1
359
邁克爾的解決方案是獲得答案的更好解決方案,我只是想幫助您了解您缺少什么以及如何使其發揮作用。
uj5u.com熱心網友回復:
解決此問題的最簡單方法是使用sum()查找已經過去的月份中的天數,然后添加額外的天數。像這樣:
def day_of_the_year(month, day):
days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return sum(days_per_month[:month-1]) day
print(day_of_the_year(1, 1)) # => 1
print(day_of_the_year(2, 1)) # => 32
print(day_of_the_year(3, 1)) # => 60
它更具可讀性和相當容易理解。無需擔心回圈(這可能會讓初學者感到困惑)。
uj5u.com熱心網友回復:
如果您的回圈位于串列理解陳述句中,是否可以接受?
如果我們假設我們在當前年份作業,那么我們可以使用 datetime 來獲取當前年份。我們可以使用日歷庫,而不是硬編碼每個月的日子。“ calendar.monthrange(year,month) ”回傳一個元組,其索引為 1 的元素表示指定月份的天數。有了這些部分,就可以很簡單地列出前幾個月的天數并將它們總結起來。
from datetime import datetime
import calendar
def day_of_the_year(month, day):
year = datetime.now().year
days = sum([calendar.monthrange(year, m)[1] for m in range(1, month)]) day
return days
print(day_of_the_year(1, 1)) # => 1
print(day_of_the_year(2, 1)) # => 32
print(day_of_the_year(3, 1)) # => 60
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/521412.html
