“count.get”是什么意思? Leetcode 347 中的平均值。前 K 个频繁元素
在问题的解决方案中(Leet代码347.前K个频繁元素)
给定一个整数数组nums和一个整数k,返回k个最频繁的元素。您可以按任何顺序返回答案。
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k == len(nums):
return nums
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)
我无法理解
key=count.get
最后一行的含义。
当输入是
nums = [1,1,1,2,2,3], k = 2
答案时应该是
[1,2]
如果我
key=count.get
从最后一行剪切, 输出将是
[3,2]
谁能教我“count.get”的作用吗?
In the solution of the problem (Leet code 347. Top K Frequent Elements)
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k == len(nums):
return nums
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)
I cannot understand what
key=count.get
means at the last line.
When the input is
nums = [1,1,1,2,2,3], k = 2
the answer should be
[1,2]
If I cut
key=count.get
from the last line,
the output would be
[3,2]
Could anyone teach me what "count.get" does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论