【问题标题】:how to tell which key has the most value stored in a dictionary如何判断哪个键在字典中存储的值最多
【发布时间】:2018-06-26 01:37:01
【问题描述】:

我有一个完整的程序,其中包含以前的字典,具有不同的功能,可以为我提供飞机出发和到达城市的列表。

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

def 出境(航班): 长度 = 0 我在(航班): 如果(len(航班 [i])> 长度): 长度 = (len(航班[i])) 休息 别的: 继续

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


    【解决方案1】:

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

    【讨论】:

    • def 传出(flights): length = 0 for i in (flights): if (len(flights[i]) > length): length = (len(flights[i])) break else : continue for i in flight: if (len(flights[i]) == length): pop = (len(flights[i])) print ("最离港的航班是:" , [i]) 我试过这个这应该可以工作,但由于某种原因,它没有给我文件中的最大值。任何想法为什么?
    • 我不确定你的缩进,但这个值总是给你第一次飞行吗?我不认为你想要一个 break 语句。
    【解决方案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,但从您的问题来看,您似乎想要 到达人数最多的城市​s,而不仅仅是一个最多的城市。使用sort 还可以让您判断是否有平局。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 2015-03-29
      • 2010-11-02
      • 2013-09-20
      • 1970-01-01
      相关资源
      最近更新 更多