Python – 限制列表中的元素频率
给定一个列表和元素频率列表,从频率列表中限制列表中元素的频率。
Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 1}
Output : [1, 4, 5, 4, 4, 6]
Explanation : Limit of 1 is 1, any occurrence more than that is removed. Similar with all elements.
Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 2, 1 : 1, 6 : 1, 5 : 1}
Output : [1, 4, 5, 4, 6]
Explanation : Limit of 4 is 3, any occurrence more than that is removed. Similar with all elements.
方法:使用循环 + defaultdict()
在此,我们迭代元素并使用 defaultdict() 维护每个元素的查找计数器,如果任何元素超过限制字典,则不再添加该元素。
Python3
# Python3 code to demonstrate working of
# Restrict Elements Frequency in List
# Using loop + defaultdict()
from collections import defaultdict
# initializing list
test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing restrct_dict
restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 2}
res = []
lookp = defaultdict(int)
for ele in test_list:
lookp[ele] += 1
# move to next ele if greater than restrct_dict count
if lookp[ele] > restrct_dict[ele]:
continue
else:
res.append(ele)
# printing results
print("Filtered List : " + str(res))
输出
The original list is : [1, 4, 5, 4, 1, 4, 4, 5, 5, 6]
Filtered List : [1, 4, 5, 4, 4, 5, 6]