我已经试着做了一段时间了,已经有一部分实现了,但还没有完全实现。我在用两本字典。我的字典如下,第一本字典的值代表:任职年份和任职年限。第二个字典(这里缩短到只有3年,太大了,不能把所有的东西都放在这里),键代表年份,值按月份(0到11)表示失业人数:
pres={"Reagan": (1981, 8), "Bush":(1989, 4),
"Bill Cliton":(1993,8,}
unemploy= {
1989: (6682, 6359, 6205, 6468, 6375, 6577, 6495, 6511, 6590, 6630, 6725, 6667),
1990: (6752, 6651, 6598, 6797, 6742, 6590, 6922, 7188, 7368, 7459, 7764, 7901),
1991: (8015, 8265, 8586, 8439, 8736, 8692, 8586, 8666, 8722, 8842, 8931, 9198),
1992: (9283, 9454, 9460, 9415, 9744, 10040, 9850, 9787, 9781, 9398, 9565, 9557) }
我一直在试图得到平均失业率,如果我呼吁一个总统,例如里根。我到目前为止的进展:
def avg_unemployment_for_president (pres,unemploy,president):
total=0
avg=0
for key,value in pres.items():
if key == president:
firstyear= value[0]
lastyear=value[0]+ value[1]
if (firstyear, lastyear) in unemploy.keys():
for x in range(firstyear,lastyear):
allunemp = unemploy[x]
listunemp=list(allunemp)
total= sum(listunemp)
return(total)
avg_unemployment_for_president(pres, unemploy "Reagan")
如何让它从第一年开始迭代,并将每年的元组值中的所有值一直添加到年底?我希望得到的产出是服务年限内的月平均失业率。你知道吗
我只做了一年的月平均值:
def avg_unemployment_for_month(unemploy,month):
sum = 0
avg=0
if (0>month) or (month > 11):
return None
else:
for m in unemploy.values():
sum += m[month]
average=sum / len(unemploy)
avg=int(average)
return (avg)
一年的失业率:
def total_unemployment_for_year(unemploy,year):
total = 0
if year in unemploy.keys():
allunemp = unemploy[year]
listunemp=list(allunemp)
totalunemp= sum(listunemp)
return(totalunemp)
理解和使用内置的^{} 将有助于:
schwobasegll的答案非常好而且简短,但是如果您需要函数格式的话,请看下面。你知道吗
相关问题 更多 >
编程相关推荐