首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在字典中迭代字符串和浮动以求最小值的问题

在字典中迭代字符串和浮动以求最小值的问题
EN

Stack Overflow用户
提问于 2022-04-28 07:24:20
回答 2查看 44关注 0票数 1

我需要你的帮助,解决可迭代和不可迭代的值,以找到最小值。

输入:

D1={“Arcadia”:{“月份”:“一月”、“大气压(HPa)”:1013.25}、“Xanadu”:{“一月”、“大气压(HPa)”:“无信息”}、“亚特兰蒂斯”:{“月份”:“一月”、“大气压(HPa):2035.89}”}

输出:

气压最低的城市是阿卡迪亚,气压为1013.25。

这是我的密码:

代码语言:javascript
运行
复制
 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)

如果有字典理解的话,我也想知道。

再次感谢大家。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-28 07:42:23

将字典内容编辑成我认为应该是的内容后,生成的代码就足够了:

代码语言:javascript
运行
复制
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')

输出:

代码语言:javascript
运行
复制
The city with the lowest pressure is Arcadia with the Atmospheric Pressure of 1013.25
票数 1
EN

Stack Overflow用户

发布于 2022-04-28 07:44:21

代码语言:javascript
运行
复制
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}')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72039603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档