互联网面试宝典

您现在的位置是: 首页 > 数据结构

问题详情

编写一个函数,返回一组字符串中出现频率最高的前 k 个字符串及其出现次数

面试宝典 2023-06-12 Web前端开发工程师 40
以下是Python代码实现:

```python
def top_k_frequent_words(words, k):
freq_dict = {}
for word in words:
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
sorted_freq = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)
return sorted_freq[:k]
```

函数接收一个字符串列表 `words` 和一个整数 `k`,并返回出现频率最高的前 `k` 个字符串及其出现次数。首先遍历字符串列表,使用字典 `freq_dict` 统计每个字符串的出现次数。然后使用 `sorted` 函数通过字典的值对 `freq_dict` 进行排序,并取前 `k` 个元素返回即可。

注意,如果有多个字符串出现次数相同,则按照字典序排序。如果要按照出现次数排序,可以将 `key=lambda x: x[1]` 修改为 `key=lambda x: (-x[1], x[0])`。