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

2024-04-25 01:46:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个完整的程序,在一个不同的功能,给我一个起飞和抵达城市的飞机列表以前的字典。你知道吗

我正在尝试编写一个函数来确定哪些键具有最多的传出航班,但我无法找出如何找到哪些键具有最多的值。我的字典叫flights,它以出发城市为关键字,以到达城市为值。你知道吗

def出发(航班): 长度=0 对于i in(航班): if(len(flights[i])>;长度): 长度=(len(航班[i])) 打破 其他: 继续

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

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

这段代码应该可以工作,但由于某些原因,它没有从文件中提供正确的最大输出。你知道为什么吗?你知道吗


Tags: 函数ingt程序功能列表forlen
2条回答

你不太清楚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还可以告诉您是否有领带。你知道吗

最简单的解决方案是只使用内置的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])

相关问题 更多 >