繁体   English   中英

如何在列表中找到 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 个受欢迎的项目。

您可以将度数视图转换为字典并使用collections.Counter.most_common方法:

import networkx as nx
from collections import Counter
lst = [('a','b'), ('a','c'), ('b','e'), ('a','d')]
G=nx.Graph()
G.add_edges_from(lst)
degrees = G.degree()
most_common = Counter(dict(degrees)).most_common(1)

Output:

('a', 3)

似乎您想了解networkx但对于您的具体问题,您甚至不需要创建图表,您可以简单地展平列表并计算元素:

from itertools import chain
from collections import Counter
counts = Counter(chain.from_iterable(lst))
counts.most_common(1)

您想使用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

Output: [('a', 3), ('b', 2)]

仅按频率降序获取密钥:

c = Counter(chain.from_iterable(l))

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

Output: ['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])

OUTPUT

['a', 'b']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM