简体   繁体   English

Python 没有结果和 KeyError:1

[英]Python got no result and KeyError:1

def fre(dic, k):
    max_k = dic.keys()[0]
    max_v = dic.values()[0]
    while len(dic2) < k:
        for key, value in dic.items():
            if max_v < value:
                max_k = key
                max_v = value

        dic2[max_k] = max_v
        del dic[max_k]
    return dic2
# dic is a dictionary, k is an int

This question is to get the k biggest value in dic and get the matched key :value pairs.这道题是获取dic中的k个最大值,并获取匹配的key:value对。 But I got running problem and got KeyError: 1.但是我遇到了运行问题并得到了 KeyError: 1。

The problem is that, each time through the loop, you leave max_k and max_v to the key-value pair you just found.问题是,每次循环时,您将max_kmax_v留给您刚刚找到的键值对。

Since that was the maximum value, no other value in the dictionary will be larger.由于这是最大值,字典中没有其他值会更大。 So at the end of the loop, you'll still have the same max_k and max_v .因此,在循环结束时,您仍将拥有相同的max_kmax_v And then you'll try to del dic[max_k] again, and it raises a KeyError , because you already deleted it.然后你会再次尝试del dic[max_k] ,它会引发一个KeyError ,因为你已经删除了它。

The solution is simple: take the code that sets max_k and max_v to the first element, and move it into the outer loop, so it runs every time instead of just the first time:解决方案很简单:将设置max_kmax_v为第一个元素的代码移到外循环中,这样它每次都运行,而不是第一次运行:

while len(dic2) < k:
    max_k = dic.keys()[0]
    max_v = dic.values()[0]

    for key, value in dic.items():
        if max_v < value:
            max_k = key
            max_v = value

    dic2[max_k] = max_v
    del dic[max_k]

But, while we're at it, there are easier (or at least harder-to-get-subtly-wrong) ways to do this.但是,虽然我们正在这样做,但有更简单(或至少更难弄巧成拙)的方法来做到这一点。

The most obvious is to just sort the items by value , then take the first k :最明显的是按 value 对项目进行排序,然后取第一个k

import operator

def fre(dic, k):
    return dict(sorted(dic.items(), key=operator.itemgetter(1), reverse=True)[:k])

For more on how key functions work, and that itemgetter , see the Sorting HOWTO .有关关键函数如何工作以及itemgetter ,请参阅Sorting HOWTO

But you can make this more efficient.但是你可以使这更有效。 sorted obviously has to sort all n values, just to get the top k , so it takes O(n) space and O(n log n) time. sorted显然必须对所有n值进行排序,只是为了得到前k ,所以它需要O(n)空间和O(n log n)时间。 If k is a lot smaller than n , you can do a lot better by using heapq.nlargest , which takes only O(k) space and O(n log k) time:如果kn小很多,你可以通过使用heapq.nlargest做得更好, heapq.nlargest需要O(k)空间和O(n log k)时间:

import heapq
import operator

def fre(dic, k):
    return dict(heapq.nlargest(k, dic.items(), key=operator.itemgetter(1)))

Either way, this doesn't delete the keys from dic ;无论哪种方式,这都不会从dic删除键; if you need that, you can do that manually:如果需要,您可以手动执行此操作:

def fre(dic, k):
    dic2 = dict(heapq.nlargest(k, dic.items(), key=operator.itemgetter(1)))
    for key in dic2:
        del dic[key]
    return dic2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM