📌  相关文章
📜  Python|从元组列表中查找前 K 个频繁元素

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

Python|从元组列表中查找前 K 个频繁元素

给定一个元组列表,其中单词作为第一个元素,其频率作为第二个元素,任务是找到前k个频繁元素。

以下是实现上述任务的一些方法。

方法 #1:使用defaultdict

# Python code to find top 'k' frequent element
  
# Importing
import collections
from operator import itemgetter
from itertools import chain
  
# Input list initialization
Input =[[('Name', 151)], [('ACe', 400)],
        [('TURN', 210)], [('RED', 1113)],
        [('YELLOW', 1)]]
  
# K initialization
K = 3
  
# Using defaultdict to  find top 'k' frequent element
dict_ = collections.defaultdict(list)
new_list = list(chain.from_iterable(Input))
  
for elem in new_list:
    dict_[elem[0]].append(elem[1])
  
res = {k: sum(v) for k, v in dict_.items()}
  
# Using sorted
Output = sorted(res.items(), key = itemgetter(1),
                             reverse = True)[0:K]
  
# printing output
print("Initial List of tuple is", Input)
print("\nTop 'K' elements are", Output)
输出:


方法 #2:使用itertoolssorted

# Python code to find top 'k' frequent element
from operator import itemgetter
from itertools import chain
  
# Input list initialization
Input =[[('Name', 151)], [('ACe', 400)],
        [('TURN', 210)], [('RED', 1113)],
        [('YELLOW', 1)]]
  
# k initialization
K = 3
  
# Finding top 'k' frequent element 
# without using collection
Output = sorted(list(chain.from_iterable(Input)),
        key = itemgetter(1), reverse = True)[0:K]
  
# Printing Output
print("Initial List of tuple is", Input)
print("\nTop 'K' elements are", Output)
输出: