Python – 提取频率大于 K 的元素
给定一个 List,提取所有频率大于 K 的元素。
Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 3, 8], K = 3
Output : [4, 3]
Explanation : Both elements occur 4 times.
Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6], K = 2
Output : [4, 3, 6]
Explanation : Occur 4, 3, and 3 times respectively.
方法 #1:使用 count() + 循环
在此,我们使用 count() 来获取频率,并使用循环来迭代 List 的每个元素。
Python3
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using count() + loop
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
res = []
for i in test_list:
# using count() to get count of elements
freq = test_list.count(i)
# checking if not already entered in results
if freq > K and i not in res:
res.append(i)
# printing results
print("The required elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using list comprehension + Counter()
from collections import Counter
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
# using list comprehension to bind result
res = [ele for ele, cnt in Counter(test_list).items() if cnt > K]
# printing results
print("The required elements : " + str(res))
输出
The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
The required elements : [4, 3]
方法 #2:使用列表理解 + Counter()
在此,我们使用 Counter() 执行计数任务,迭代部分在列表推导中完成。
Python3
# Python3 code to demonstrate working of
# Extract elements with Frequency greater than K
# Using list comprehension + Counter()
from collections import Counter
# initializing list
test_list = [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
# printing string
print("The original list : " + str(test_list))
# initializing K
K = 2
# using list comprehension to bind result
res = [ele for ele, cnt in Counter(test_list).items() if cnt > K]
# printing results
print("The required elements : " + str(res))
输出
The original list : [4, 6, 4, 3, 3, 4, 3, 7, 8, 8]
The required elements : [4, 3]