我试图以城市和温度的形式接受用户输入,然后将其保存到字典中。在那之后它应该打印出最低温度是什么以及它是什么城市。虽然我的程序从未到达打印消息,但我试图在没有min函数的情况下迭代地执行此操作。为什么以及如何解决这个问题?谢谢。
编辑:我意识到我可以使用min函数来使这更容易,但这是一个练习练习,我应该通过迭代找到最小值。此外,如果暂时不说,如果2个或更多城市的温度最低,我会忽略。
def main():
city = {}
lowest = 0
while True:
user = input("Enter city followed by temperature: ")
if user == "stop":
print(city)
for value in city.values():
if int(value) < lowest:
lowest = int(value)
for key in city:
if city[key] == lowest:
print("The coldest city is,", city[key])
break
name, temperature = user.split()
city[name] = temperature
main()
答案 0 :(得分:1)
您的代码中的问题是您将lowest
初始化为0
。如果您的所有城市都有正温度,lowest
在计算最小值时将永远不会改变,并且任何城市都不会满足if city[key] == lowest:
测试。
解决此问题的方法是将lowest
初始化为城市的其中一个温度。例如,您可以添加:
lowest = temperature
以下
if user == "stop":
将lowest
初始化为用户输入的最后一个温度。
最后,代码中的最后一个问题出现在if city[key] == lowest
测试中:构建字典的方式,city[key]
是一个字符串,而lowest
是一个整数,它们永远不会相等。我建议你在构造字典时将温度转换为整数,这样你就不必在以后处理转换。整体更正后的代码如下所示:
def main():
city = {}
while True:
user = input("Enter city followed by temperature: ")
if user == "stop":
print(city)
lowest = temperature
for value in city.values():
if value < lowest:
lowest = value
for key in city:
if city[key] == lowest:
print("The coldest city is,", city)
break
name, temperature = user.split()
temperature = int(temperature)
city[name] = temperature
main()
答案 1 :(得分:0)
找到最低点的更简单方法是使用min
lowest = min(city.values())
“停止”应该break
离开你的循环
while True:
user = input("Enter city followed by temperature: ")
if user == "stop":
break
name, temperature = user.split()
city[name] = float(temperature) # convert to float (or perhaps int)
print(city)
lowest = min(city.values())
for key in city:
if city[key] == lowest:
print("The coldest city is,", city[key])
当有多个温度最低的城市
时,您可能需要考虑打印不同的消息答案 2 :(得分:0)
您可以使用传递lambda到min来直接获取键/值。
while True:
user = input("Enter city followed by temperature: ")
if user == "stop":
break
name, temperature = user.split()
city[name] = float(temperature) # convert to float (or perhaps int)
lowest_city, lowest_temp = min(city.iteritems(), key=lambda x:x[1])
print("The coldest city is, %s, temperature = %.3f" % (lowest_city, lowest_temp))
这里lambda函数告诉min函数根据选择 iteritems函数返回的元组的第二个值。