所以我正在用dataquest.io学习python。我刚刚完成了初学任务。我认为我已经完成的挑战问题之一(下面的代码)是:
编写一个函数,在多年内提取相同的值 计算连续值之间的差异以显示是否 出生人数正在增加或减少。例如,怎么做了 星期六的出生人数在1994年至2003年间每年都有变化?
然而,我如何才能得到它,以便打印结果告诉读者时间段。例如,column == 1
时,值1表示1月。但是,当column == 2
时,值为1表示“本月的第1天”。那么什么价值意味着什么取决于什么列。我怎样才能有意义地向读者传达这一点,以及我下次所知道的内容。只是编写一长串if
和and
语句?
谢谢!
我的代码:
# year,month,date_of_month,day_of_week,births
# 0 1 2 3 4
def year_range(start_year, end_year):
# years must be bewtween 1994 and 2003
if end_year > 2003:
print ("End year too high")
return
if start_year < 1994:
print ("Start year too low")
return
# for each year from start to end
years = []
for x in range(end_year - start_year + 1):
years.append(start_year + x)
return years
def yearly_diffs(data, column, value, start_year, end_year):
# column = 0-3
# value depends on col, but 1-6 are always okay
if column == 0:
period = 'year'
if column == 1:
period = 'month'
if column == 2:
period = 'day of month'
if column ==3:
period = 'day of week'
years = year_range(start_year, end_year)
period_births = {}
for year in years:
period_births[year] = 0
for x in data:
births = x[4]
if x[0] == year and x[column] == value:
period_births[year] += births
changes = {}
for x in years:
if x != start_year:
changes[x] = period_births[x] - period_births[x-1]
print ('Here are the yearly values for births for:\n{} (period)\n{} (value in period)'.format(period, value))
return period_births, changes
答案 0 :(得分:0)
听起来像列表列表的工作。
period = [
range(3000),
[None, 'January', 'February', ...],
[None, '1st of the month', '2nd of the month', ...],
[None, 'Sunday', 'Monday', ...]
]
print(period[column][value])
column
变量选择适当的内部列表,value
变量对其进行索引。不需要if
。前面的None
帐户表示您的值从1开始而不是0. range(3000)
处理年份。