字典以及为什么我一直打印每个结果

时间:2013-11-15 06:14:27

标签: python dictionary process

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

[(-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])

3 个答案:

答案 0 :(得分: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])

答案 1 :(得分:1)

您应首先附加所有项目,然后应用sort:

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 

答案 2 :(得分:1)

为什么你需要一个dictlistset可能更有意义

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)))