树状结构序列号的兄弟节点计数功能实现求助
问题描述
我有一组字符串类型的树状结构序列号,点号代表树的层级,需要统计每个序列号的兄弟节点数量。
示例输入列表:
node_list = ["33.1", "33.5", "33.15", "33.1.1", "33.1.2", "33.1.11", "34.5", "33.2.9"]
我尝试的代码如下:
list = ["33.1", "33.5", "33.15", "33.1.1", "33.1.2", "33.1.11", "34.5", "33.2.9"] for item in list: numberOfSiblings = 0 splitText = item.rsplit(".", 1) j = 0 while( j < len(list)): if( list[j].startswith(splitText[0]) and len(item) == len(list[j]) and item != list[j] ): numberOfSiblings +=1 j+=1 print(numberOfSiblings)
期望输出:
33.1 => 2 33.5 => 2 33.15 => 2 33.1.1 => 2 33.1.2 => 2 33.1.11 => 2 34.5 => 0 33.2.9 => 0
当前代码的问题出在while循环中的长度检查部分:len(item) == len(list[j])会错误排除长度不同但属于同一层级的兄弟节点(比如"33.1"和"33.15"),导致计数错误。
修复方案
核心思路是:兄弟节点的定义是同一父节点下、层级相同的其他节点,应该通过拆分路径来判断,而非依赖字符串长度。
方法一:高效分组统计
先对所有节点按「父路径+层级数」分组,统计每组的节点数量,每个节点的兄弟数即为对应组的数量减1(减去自身)。该方法时间复杂度为O(n),适合大规模数据。
代码实现:
node_list = ["33.1", "33.5", "33.15", "33.1.1", "33.1.2", "33.1.11", "34.5", "33.2.9"] # 构建分组字典:key为(父路径, 层级数),value为该组节点数量 group_counts = {} for node in node_list: parts = node.split('.') level = len(parts) parent_path = '.'.join(parts[:-1]) if level > 1 else '' key = (parent_path, level) group_counts[key] = group_counts.get(key, 0) + 1 # 遍历节点计算兄弟数 for node in node_list: parts = node.split('.') level = len(parts) parent_path = '.'.join(parts[:-1]) if level > 1 else '' key = (parent_path, level) sibling_count = group_counts[key] - 1 print(f"{node} => {sibling_count}")
方法二:直接遍历校验(适合小列表)
如果列表规模不大,可直接遍历每个节点,逐个校验是否符合兄弟节点条件:
node_list = ["33.1", "33.5", "33.15", "33.1.1", "33.1.2", "33.1.11", "34.5", "33.2.9"] for item in node_list: sibling_count = 0 item_parts = item.split('.') item_level = len(item_parts) item_parent = '.'.join(item_parts[:-1]) if item_level > 1 else '' for other in node_list: if other == item: continue other_parts = other.split('.') other_level = len(other_parts) other_parent = '.'.join(other_parts[:-1]) if other_level > 1 else '' # 层级相同且父路径一致即为兄弟 if other_level == item_level and other_parent == item_parent: sibling_count += 1 print(f"{item} => {sibling_count}")
两种方法均能输出符合预期的结果。
内容的提问来源于stack exchange,提问作者Masoom Raza
相关产品推荐
相关产品推荐

