📜  Python|提取最小频率元素

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

Python|提取最小频率元素

有时,在处理数据时,我们可能会遇到需要提取列表中出现次数最少的元素的问题。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用defaultdict() + 循环
上述功能的组合可用于执行此任务。在此,我们使用 defaultdict() 提取每个元素的频率,并在遍历 defaultdict 后提取最小频率元素。

# Python3 code to demonstrate working of
# Extract least frequency element
# using defaultdict() + loop
from collections import defaultdict
  
# initialize list 
test_list = [1, 3, 4, 5, 1, 3, 5]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract least frequency element
# using defaultdict() + loop
res = defaultdict(int)
for ele in test_list:
   res[ele] += 1 
min_occ = 9999
for ele in res:
    if min_occ > res[ele]:
        min_occ = res[ele]
        tar_ele = ele
  
# printing result
print("The minimum occurring element is : " + str(tar_ele))
输出 :
The original list : [1, 3, 4, 5, 1, 3, 5]
The minimum occurring element is : 4

方法 #2:使用Counter()
该方法与上面类似,不同之处在于使用 Counter() 存储频率,然后提取频率最低的元素。

# Python3 code to demonstrate working of
# Extract least frequency element
# using Counter()
from collections import Counter
  
# initialize list 
test_list = [1, 3, 4, 5, 1, 3, 5]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract least frequency element
# using Counter
res = Counter(test_list)
tar_ele = res.most_common()[-1][0]
  
# printing result
print("The minimum occurring element is : " + str(tar_ele))
输出 :
The original list : [1, 3, 4, 5, 1, 3, 5]
The minimum occurring element is : 4