我有一本姓名词典,以及姓名在通讯录中出现的次数:
names_dict = {
'Adam': 100,
'Anne': 400,
'Britney': 321,
'George': 645,
'Joe': 200,
'John': 1010,
'Mike': 500,
'Paul': 325,
'Sarah': 150
}
最好不要使用sorted()
,我希望遍历字典并创建一个只有前五个名称的新字典:
我似乎能够创建一个新的字典,每当我们遍历names-tu-dict并找到一个比new-dict中的值高的名称/计数时,它就会得到一个新的键/值对。但是,我不知道如何在从names-tu-dict中添加大的之后从new-dict中删除较小的
有没有更好的方法-不必导入特殊的库或使用sorted()
来迭代dict并创建具有最高值的前N个键的新dict?在
您应该使用^{} function 来实现这一点:
这使用了一个更有效的算法(对于大小为N的dict,使用O(NlogK)和K个top items)将前5个项提取为
(key, value)
元组,然后将这些元组传递给dict()
以创建新字典。在演示:
^{pr2}$您可能需要使用^{} class 。^{} method 会让你的用例变得很容易解决。该方法的实现在幕后使用
heapq.nlargest()
。在这些是而不是特殊库,它们是Python标准库的一部分。否则,您必须自己实现一个binary heap来实现这一点。除非您专门研究这个算法,否则重新实现您自己的算法是没有意义的,Python implementation对某些关键函数使用extension written in C进行了高度优化)。在
我不知道,为什么您不想使用sort,而解决方案并不完美,甚至与您的问题不完全匹配,但我希望它能激励您找到自己的实现。我认为这只是你真正问题的一个简短的例子。在
但正如你在另一个答案中看到的:通常最好是使用代码,这是在以前编写的,而不是自己去做所有的事情。在
相关问题 更多 >
编程相关推荐