【问题标题】:Get the highest values of the dictionary with keys until reaching given limit使用键获取字典的最高值,直到达到给定的限制
【发布时间】:2019-04-23 14:35:32
【问题描述】:

给定字典和新字典的键数限制。在新字典中,我们应该从给定字典中获得最多的值。

给出的是:

dict = {'apple':5, 'pears':4, 'orange':3, 'kiwi':3, 'banana':1

我想用 key 获取一个具有最高值的新字典。

新是

{'apple':5} 

因为应该只有一个

如果限制是 2。

{'apple':5, 'pears':4}

因为有三个值,但限制是 2,所以我们什么都不带。我试过了

如果限制是 3。它仍然是

{'apple':5, 'pears':4}

因为我不能添加橙色。如果我添加它将超过限制。

new = {}
while len(new) < limit:

然后我必须用新的键附加最高值,直到达到 限制。如果超过限制,我不应该添加密钥。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    你可以只使用collections.Counter()中的most_common()

    from collections import Counter
    
    def largest(dct, n):
        return dict(Counter(dct).most_common(n))
    
    print(largest(dct={'apple':5, 'pears':4, 'orange':3, 'kiwi':3, 'banana':1}, n=2))
    # {'apple': 5, 'pears': 4}
    
    print(largest(dct={'apple':5, 'pears':4, 'orange':3, 'kiwi':3, 'banana':1}, n=3))
    # {'apple': 5, 'pears': 4, 'orange': 3}
    

    甚至heapq.nlargest():

    from heapq import nlargest
    from operator import itemgetter
    
    def largest(dct, n):
        return dict(nlargest(n, dct.items(), key=itemgetter(1)))
    
    print(largest(dct={'apple':5, 'pears':4, 'orange':3, 'kiwi':3, 'banana':1}, n=2))
    # {'apple': 5, 'pears': 4}
    
    print(largest(dct={'apple':5, 'pears':4, 'orange':3, 'kiwi':3, 'banana':1}, n=3))
    # {'apple': 5, 'pears': 4, 'orange': 3}
    

    【讨论】:

    • 它不应该是 {'apple': 5, 'pears': 4, 'orange': 3} 当 n=3 时,因为如果你包括橙色,你也应该包括猕猴桃,但如果你包括kiwi 那么它会超过限制,所以我们不应该同时包含它们。
    【解决方案2】:

    整个代码是一个函数:

    def f(d,limit):
       return dict(sorted(d.items(),key=lambda x: -x[1])[:limit])
    

    现在:

    print(f(d,1))
    

    是:

    {'apple': 5}
    

    还有:

    print(f(d,2))
    

    是:

    {'apple': 5, 'pears': 4}
    

    请注意,如果字典总是像您现在拥有的字典一样按值排序,请执行以下操作:

    def f(d,limit):
        return dict(d.items()[:limit])
    

    【讨论】:

      【解决方案3】:

      我相信你的问题是你有

      while len(new) < limit: 
      

      必须是while len(new) &lt;= limit:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 1970-01-01
        相关资源
        最近更新 更多