-3

所以我写了一段代码来检测一个城市的最低温度,这取决于输入是什么,我现在的问题是我从循环的每个过程中得到每个单独的结果。因此,我最终得到的不是一份包含天气和城市的最终打印声明

[(-3, 'Toronto')]
The coldest city is: Toronto -3
[(-5, 'Edmonton'), (-3, 'Toronto')]
The coldest city is: Edmonton -5
[(-5, 'Edmonton'), (-4, 'Calgary'), (-3, 'Toronto')]
The coldest city is: Edmonton -5

我的输入是多伦多,-3 埃德蒙顿 -5,卡尔加里 -4

这是我的代码

dic = {}
for i in range(5):
        city = input("Enter city followed by temperature >")
        if (city != "stop"):       
                info = city.split()
                dic[info[0]] = int(info[1])
        elif city == "stop":
                break
print(dic) 
alist=[] 
for k,v in dic.items(): 
        alist.append((v,k)) 
        alist.sort() 
        print(alist)
        temp = alist[0]
        print("The coldest city is:",temp[1], temp[0])
4

3 回答 3

2

移动除append循环外的所有内容,因此它只执行一次,毕竟所有数据都在alist

for k,v in dic.items(): 
    alist.append((v,k)) 
alist.sort() 
print(alist)
temp = alist[0]
print("The coldest city is:",temp[1], temp[0])
于 2013-11-15T06:17:17.567 回答
1

为什么你需要一个dict?Alist或 aset可能更有意义

cities = []
for i in range(5):
    city = input("Enter city followed by temperature >")
    if city == "stop":
        break
    info = city.split()
    cities.append((int(info[1]), info[0]))

print("The coldest city is: {} {}".format(*min(cities)))
于 2013-11-15T06:36:05.483 回答
1

您应该先附加所有项目,然后再应用排序:

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

或者使用更短的版本min,这将需要O(N)时间(无需排序)。:

min(dic, key=dic.get) #Returns the key with smallest value
min(dic.items(), key = lambda x:x[1]) #return key, value pair 
于 2013-11-15T06:18:07.610 回答