如何统计列表元组表示的无向边中边数最多的节点及对应边数
实现方法
核心思路
无向边的每个节点在元组中出现的次数,就等于该节点关联的边数,我们只需要统计所有节点的出现次数,再取最大值即可。
代码实现
依赖标准库的最简实现
from collections import Counter # 你的边列表,注意不要用list作为变量名,会覆盖Python内置关键字 edges = [("a","b"), ("a","c"), ("a","d"), ("b","d"), ("c","d")] # 展开所有边的节点为一维列表 all_nodes = [node for edge in edges for node in edge] # 统计每个节点的出现次数(即边数) node_edge_count = Counter(all_nodes) # 取出边数最多的节点和对应边数 max_node, max_edge_num = max(node_edge_count.items(), key=lambda item: item[1]) print(f"边数最多的节点是{max_node},边数为{max_edge_num}")
运行示例输出:
边数最多的节点是a,边数为3
处理多节点并列最大值的场景
如果存在多个节点边数相同且均为最大值,可以用以下方式获取所有并列节点:
max_edge_num = max(node_edge_count.values()) max_nodes = [node for node, count in node_edge_count.items() if count == max_edge_num] print(f"边数最多的节点有{max_nodes},边数均为{max_edge_num}")
纯原生实现(无需导入标准库)
如果不想导入collections,也可以用字典手动统计:
edges = [("a","b"), ("a","c"), ("a","d"), ("b","d"), ("c","d")] node_edge_count = {} for u, v in edges: node_edge_count[u] = node_edge_count.get(u, 0) + 1 node_edge_count[v] = node_edge_count.get(v, 0) + 1 max_node, max_edge_num = max(node_edge_count.items(), key=lambda x: x[1]) print(f"边数最多的节点是{max_node},边数为{max_edge_num}")
内容的提问来源于stack exchange,提问作者reallycool123
相关产品推荐
相关产品推荐

