#yearly_weather
import os
from datetime import datetime, date
import datetime
test={datetime.date(1977, 6, 5): [81, 55, 0.0, False],
datetime.date(2007, 11, 18): [45, 41, 0.02, True],
datetime.date(2017, 11, 3): [43, 33, 0.3, True],
datetime.date(2007, 2, 24): [44, 36, 0.36, True],
datetime.date(2015, 2, 18): [54, 40, 0.0, False],
datetime.date(2008, 11, 18): [51, 43, 0.01, True],
datetime.date(1965, 12, 29): [43, 33, 0.27, True]}
#yearly_weather={year:[AVG_TMAX, AVG_TMIN, TOTAL_PRCP, TOTAL_RAINY_DAYS, TOTAL_DAYS]}
# datetime.date(1965, 12, 29): [43, 33, 0.27, True]}
#{2017: [45.666666666666664, 34.333333333333336, 2.28, 9, 15]}
temp={}
yearly_weather={}
for k,v in test.items():
year=k.year
value=temp.get(k.year,(0,0,0,0,0,0))
sumtmax=v[0]+value[0]
counttmax=value[1]+1
sumtmin=v[1]+value[2]
counttmin=value[3]+1
sumprcp=v[2]+value[4]
sumrainy=v[3]+value[5]
sumdays=counttmax
temp[k.year]=(sumtmax,counttmax,sumtmin,counttmin,sumprcp,sumrainy,sumdays)
#print(temp)
for k,v in temp.items():
yearly_weather[k]=(v[0]/v[1],v[2]/v[3],v[4],v[5],v[6])
print(yearly_weather)
def year_info(year, yearly_weather):
for k,v in yearly_weather.items():
if year==k:
return "{:<8.0f}| {:<18.2f}| {:>12.2f} | {:>10.2f} | {:>10.0f}| {:>10.0f}" .format(k,v[0],v[1],v[2],v[3],v[4])
else:
return "{:^8s}| {:^18s}| {:^12s} | {:^10s} | {:^10s} | {:^10s}".format("N/A","N/A","N/A","N/A","N/A","N/A")
year="1965"
year=int(year)
year_info(year,yearly_weather)
N/A | N/A | N/A | N/A | N/A | N/A
当我尝试查找特定年份的信息时, 它应该返回天气信息,为什么会变成N / A?
忽略:重复单词要求的问题 忽略:重复单词要求的问题
答案 0 :(得分:3)
无需重复字典。只需直接访问相应的词典项。如果您需要处理$foreign_id
,可以使用INSERT INTO users (first_name, surname, foreign_id) VALUES ('John', 'Smith', '{$foreign_id}')
/ KeyError
子句:
try
结果
except
答案 1 :(得分:1)
第一年是1977年,与1965年不同,因此函数返回“ N / A”。它不会检查集合中的下一个项目。
请尝试以下代码:
def year_info(year, yearly_weather):
for k,v in yearly_weather.items():
if year==k:
return "{:<8.0f}| {:<18.2f}| {:>12.2f} | {:>10.2f} | {:>10.0f}| {:>10.0f}" .format(k,v[0],v[1],v[2],v[3],v[4])
return "{:^8s}| {:^18s}| {:^12s} | {:^10s} | {:^10s} | {:^10s}".format("N/A","N/A","N/A","N/A","N/A","N/A")