我需要你的帮助,解决可迭代和不可迭代的值,以找到最小值。
输入:
D1={“Arcadia”:{“月份”:“一月”、“大气压(HPa)”:1013.25}、“Xanadu”:{“一月”、“大气压(HPa)”:“无信息”}、“亚特兰蒂斯”:{“月份”:“一月”、“大气压(HPa):2035.89}”}
输出:
气压最低的城市是阿卡迪亚,气压为1013.25。
这是我的密码:
def lowest_pressure(dict1):
dict_pressure={}
exclude = "No information"
for city,data in dict1.items():
for value in str(data["Atmospheric Pressure(hPa)"]):
if value != exclude:
dict_pressure[city]=data["Atmospheric Pressure(hPa)"]
low_pressure=min(dict_pressure,key=dict_pressure.get)
print(f"The city that has the lowest Atmospheric Pressure is {low_pressure} with ${dict_pressure[low_pressure}hPa.")
lowest_pressure(D1)如果有字典理解的话,我也想知道。
再次感谢大家。
发布于 2022-04-28 07:42:23
将字典内容编辑成我认为应该是的内容后,生成的代码就足够了:
D1 = {"Arcadia": {"Month": "January", "Atmospheric Pressure(hPa)": 1013.25},
"Xanadu": {"Month": "January", "Atmospheric Pressure(hPa)": "No information"},
"Atlantis": {"Month": "January", "Atmospheric Pressure(hPa)": 2035.89}
}
t = []
for k, v in D1.items():
try:
t.append((float(v['Atmospheric Pressure(hPa)']), k))
except ValueError:
pass
if t:
p, c = min(t)
print(f'The city with the lowest pressure is {c} with the Atmospheric Pressure of {p:.2f}')
else:
print('No valid pressure measurements available')输出:
The city with the lowest pressure is Arcadia with the Atmospheric Pressure of 1013.25发布于 2022-04-28 07:44:21
D1={"Arcadia":{"Month": "January","Atmospheric Pressure(hPa)":1013.25},"Xanadu":{"Month":"January","Atmospheric Pressure(hPa)":"No information"},"Atlantis":{"Month":"January","Atmospheric Pressure(hPa)":2035.89}}
country_pressure = {a:D1[a]["Atmospheric Pressure(hPa)"] for a in D1}
min_pressure = min([a for a in country_pressure.values() if type(a)==int or type(a) ==float])
lowest_pressure_country = None
for k,v in country_pressure.items():
if v==min_pressure:
lowest_pressure_country = k
break
print(f'The city with lowest pressure is {lowest_pressure_country}')https://stackoverflow.com/questions/72039603
复制相似问题