如何判断哪个键具有最大值存储在字典中

问题描述 投票:-1回答:2

我有一个完整的程序,它有一个不同功能的前一个字典,它给我一个飞机的出发和到达城市列表。

我正在尝试编写一个函数来确定哪些键具有最多的传出航班,而我无法弄清楚如何找到哪些键具有最多的值。我的字典被命名为航班,其中出发城市为钥匙,抵达时为值。

def out(flight):长度= 0表示i in(flight):if(len(flights [i])> length):length =(len(flights [i]))break else:continue

for i in flights:
    if (len(flights[i]) == length):
        pop = (len(flights[i]))

print ("the most outgoing flight is: " , [i])

这段代码可能会起作用,但由于某种原因,它没有从文件中给出正确的最大输出。任何想法为什么?

python dictionary key python-3.6
2个回答
0
投票

最简单的解决方案是使用内置的max函数和列表理解:

def outgoing(flights):
    print(max([len(i) for i in flights]))

如果您想坚持使用代码,则需要与每次迭代的最大值进行比较:

def outgoing(flights): 
    max_outgoing = 0 
    for i in flights:  
        if(max_outgoing < len(flights[i])):
            print(max_outgoing)
            max_outgoing = len(flights[i])

编辑:重新阅读你的问题,似乎你也想得到最大值的关键。这样做:

def outgoing(flights): 
    max_outgoing = 0 
    max_key = None
    for i in flights:  
        if(max_outgoing < len(flights[i])):
            print(max_outgoing)
            max_outgoing = len(flights[i])
            max_key = i

或者在较短的版本中:

def outgoing(flights):
    out_dict = {i: len(i) for i in flights}
    max_out = max(out_dict, key=out_dict.get)
    print(max_out)
    print(flights[max_out])

0
投票

你不是很清楚flights的结构,所以我假设它是键是字符串,值是字符串列表。

一种方法是创建一个元组列表,其中每个元素都是(departure_city, len(flights[departure_city]))。然后,您可以按到达次数对列表进行排序。

def outgoing(flights):
    # Create a list of tuples
    flight_tups = [(departure_city, len(flights[departure_city])) for departure_city in flights]

    # Sort the list by number of arrivals
    #   We do this by passing a lambda to `sort`,
    #   telling it to sort by the second value in
    #   each tuple, i.e. arrivals
    flight_tups.sort(key=lambda tup: tup[1])

    # We can now get the city with the most arrivals by
    #   taking the first element of flight_tups
    most = flight_tups[0]
    print(f'City: {most[0]}\nNumber of Arrivals: {most[1]}')

注意:你也可以使用max,但是根据你的问题,你似乎想要拥有最多人数的城市,而不仅仅是最多的城市。使用sort也可以让你知道是否有平局。

© www.soinside.com 2019 - 2024. All rights reserved.