【问题标题】:using dictionary to find min temperature among cities使用字典查找城市之间的最低温度
【发布时间】:2013-11-14 22:20:51
【问题描述】:

我正在尝试制作一个程序,根据给定的数据找到最低温度。 这是我到目前为止的程序,但它给出了随机结果 - 有时是最大值,有时是最小值。有人可以帮我解决它。

d = {} 

for i in range(5):
    user = input("Enter city followed by temperature > ")
    if(user!='stop'):
        data = user.split()
        d[data[0]]=int(data[1])
    else: 
        break

alist=[] 

for k,v in d.items():
    alist.append((v,k))
    alist.sort() 
    t=alist[0] 
    print("The coldest city is:",t[1],t[0])
    print(d)
    break

【问题讨论】:

  • 请缩进你的代码...
  • 如果你能更好地格式化你的代码以及你应该得到的东西,这将对我们有很大帮助。
  • 我缩进了前几行(我可以确定的那些)以正确格式化代码。请修复您的其余代码。您可以将代码粘贴到编辑器中,选择所有代码,然后单击工具栏上的{} 按钮以使其格式正确。
  • soory im new 这个更好吗?
  • 首先,你为什么要接受放入循环?您正在覆盖值

标签: python python-3.x dictionary


【解决方案1】:

我认为您的问题是,在将数据放入字典结构后,您将其作为元组附加到列表中并尝试对元组进行排序。按值对字典进行排序要容易得多。试试这个。

d = {} 
for i in range(5):
    user = input("Enter city followed by temperature > ")
    if(user!='stop'):
        data = user.split()
        d[data[0]]=int(data[1])
    else: 
        break
#Get an ordered list of tuples sorted by the temp
d_sorted = sorted(d.items(), key=lambda x: x[1]) 
coldest = d_sorted[0] 
print("The coldest city is:",coldest[0],coldest[1])

【讨论】:

  • 这比我想做的要容易得多
  • 是否可以根据气温下降得到城市列表
  • @user2994135 当然可以。得到 d_sorted 后,只需添加以下行: d_sorted_decreating = d_sorted.reverse() 这将为您提供按降序排序的元组列表。
【解决方案2】:

字典中的项目是无序的。他们的顺序可能会随着运行而变化。但是您的代码(以for k,v in d.items(): 开头)采用d.items() 返回的第一个值,将其添加到列表中,对single-itemed 列表进行排序,从列表中获取第一个也是唯一的值,打印它并中断循环。

您可以改用min() 函数来查找最冷的城市:

coldest_city = min(d, key=d.get) # find minimum in a dictionary by value
print("The coldest city is:", coldest_city, d[coldest_city])

如果您不能使用min() 函数,您可以使用简单的for-loop 来查找对应于字典中最小值的键:

it = iter(d.items()) # get an iterator over (key, value) pairs of the dictionary
minkey, minvalue = next(it) # assume dictionary is not empty
for key, value in it:
    if minvalue > value:
       minkey, minvalue = key, value
print("The coldest city is:", minkey, minvalue)

如果最低温度出现在不止一个城市,那么其中任何一个都可能被选为最冷的城市。

【讨论】:

  • 我不能只使用 min() 函数的字典,这说明为什么它对我来说要复杂得多
  • @user2994135:我添加了不使用min()的解决方案。
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
相关资源
最近更新 更多