如何在列表中找到 N 个最常出现的元素?

How to find the N most common occurring element in a list?

我有一个很大的元组列表,例如 [('a','b'), ('a','c'), ('b','e'), ('a','d')],我想在此列表中找到前 N 个热门条目。最受欢迎的是重复次数最多的那个。这里最受欢迎的两个是 ab。如果列表项的数量是百万大小,我如何利用networkx来解决这个问题?

import networkx as nx
lists = [('a','b'), ('a','c'), ('b','e'), ('a','d')]
G=nx.Graph()
G.add_edges_from(pair_names)
nx.degree(G)

这给了我受欢迎的列表,但我无法显示前 N 个受欢迎的项目。

您想使用 networkx 的任何特定原因?

您可以简单地使用 collections.Counteritertools.chain 来实现:

from collections import Counter
from itertools import chain

l = [('a','b'), ('a','c'), ('b','e'), ('a','d')]

Counter(chain.from_iterable(l)).most_common(2)

注意。这里是前 2

输出:[('a', 3), ('b', 2)]

只获取按频率降序排列的键:

c = Counter(chain.from_iterable(l))

list(dict(c.most_common(2)))

输出:['a', 'b']

您可以只使用 for 循环遍历度数。

import networkx as nx
lists = [('a','b'), ('a','c'), ('b','e'), ('a','d')]
G=nx.Graph()
G.add_edges_from(lists)
N = 2
dvweight = nx.degree(G)
popular_nodes = [nodes[0] for nodes in dvweight]
print(popular_nodes[:N])

输出

['a', 'b']