Python程序:查找列表中至少出现k次的元素


假设我们有一个名为nums的元素列表和一个值k。我们必须找到至少出现k次的元素。

因此,如果输入类似于nums = [2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1] k = 3,则输出将为[2, 5, 6, 3]

为了解决这个问题,我们将遵循以下步骤:

  • c := 包含nums中每个元素频率的列表
  • res := 一个新的列表
  • 对于c中的每个键n,执行:
    • 如果c[n] >= k,则
      • 将n插入res的末尾
  • 返回res

示例

让我们看一下下面的实现,以便更好地理解:

Open Compiler
from collections import Counter def solve(nums, k): c = Counter(nums) res = [] for n in c: if c[n] >= k: res.append(n) return res nums = [2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1] k = 3 print(solve(nums, k))

输入

[2,5,6,2,6,1,3,6,3,8,2,5,9,3,5,1], 3

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

[2, 5, 6, 3]

更新于:2021年10月12日

259 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告