You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在函数内使用networkx的predecessors方法返回错误结果问题

问题原因分析
  • 核心问题出在你自定义函数的参数判断逻辑上:Python 中整数0属于假值,你写的if temporal_index:判断语句,当传入temporal_index=0时,条件会被判定为不成立,直接走else分支返回所有父节点,根本没有执行你写的过滤逻辑,所以得到了全部两个父节点的结果。
  • 你在函数外执行的代码直接做了后缀匹配过滤,所以只返回了符合条件的Z_0,两者自然结果不一致。
修复方案
  • 把参数判断逻辑修改为判断是否为None即可,修改后的函数参考如下:
def node_parents(node: str, temporal_index: int = None) -> tuple:
    # 返回节点的父节点,支持按时间索引可选过滤
    if temporal_index is not None: # 仅修改此处判断条件即可
        # 如果你需要严格匹配下划线后的整个时间索引,推荐用split写法,避免endswith匹配到多位后缀的末尾
        return (*[v for v in  G.predecessors(node) if v.split("_")[1] == str(temporal_index)],)
        # 如果你确定所有节点的时间索引都是1位,也可以保留endswith写法
        # return tuple(filter(lambda x: x.endswith(str(temporal_index)), G.predecessors(node)))
    else:
        return tuple(G.predecessors(node))
  • 额外提醒:endswith(str(temporal_index))和split("_")[1] == str(temporal_index)的逻辑并不等价。比如存在节点A_10时,传入temporal_index=0,前者会错误匹配到该节点,后者则会正确过滤掉,建议根据你的节点命名规则选择合适的匹配方式。

内容的提问来源于stack exchange,提问作者Astrid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:36:05