📌  相关文章
📜  Python|删除频率最高为 K 的元素

📅  最后修改于: 2022-05-13 01:55:10.876000             🧑  作者: Mango

Python|删除频率最高为 K 的元素

有许多方法可以用来执行列表中的删除。无论是删除函数,弹出函数和许多其他功能。但大多数时候,我们通常不会处理简单的删除,而是有一定的约束。本文讨论了某些方法,我们可以只删除那些出现少于 K 次的元素。

方法 #1:使用列表理解 + count()
这里应用的想法是使用列表推导构造一个新列表,并仅插入那些出现超过 K 次的元素。计数操作是在计数函数的帮助下完成的。

# Python3 code to demonstrate
# remove elements less than and equal K 
# using list comprehension + count()
  
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K
K = 2
  
# using list comprehension + count()
# remove elements less than K 
res = [ i for i in test_list if test_list.count(i) > K]
  
# print result
print("The list removing elements less than and equal K  : " + str(res))
输出 :
The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K  : [3, 2, 3, 3, 2, 2, 2]

方法 #2:使用Counter() + 列表推导
使用 Counter函数可以有效地解决这个问题,该函数预先计算列表中每个元素的计数,以便保留或拒绝特定元素的决定花费更少的时间。

# Python3 code to demonstrate
# remove elements less than and equal K 
# using Counter() + list comprehension
from collections import Counter
  
# initializing list
test_list = [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K
K = 2
  
# using Counter() + list comprehension
# remove elements less than K 
freq = Counter(test_list)
res = [ele for ele in test_list if freq[ele] > K]
  
# print result
print("The list removing elements less than and equal K  : " + str(res))
输出 :
The original list : [1, 4, 3, 2, 3, 3, 2, 2, 2, 1]
The list removing elements less than and equal K  : [3, 2, 3, 3, 2, 2, 2]