【问题标题】:how to trace from target to source data in python?如何在python中从目标数据跟踪到源数据?
【发布时间】:2021-08-01 01:42:30
【问题描述】:

我想在下面的输入中遍历列表/字典中的每个数据

{mapping1: [(b,c),(a,b),(c,d)],mapping2: [(a,b),(b,c),(e,f),(d,e),(c,f)]}

对于映射,1 d 是目标,一个是源

对于映射 2:f 是目标,a 和 d 是源。

因此,此链接或跟踪可能会有所不同。

以下是我的意见

{mapping1: [(b,c),(a,b),(c,d)],mapping2: [(a,b),(b,c),(e,f),(d,e),(c,f)]}

输出是:

【问题讨论】:

  • 可以有多个来源吗?
  • 是的,可以有多个来源。 @TharunK

标签: python list dictionary python-3.7 traversal


【解决方案1】:

你可以利用有向无环图的概念,找到没有出度的节点即目标,以及没有入度的节点即源

对于python,我使用networkx来构建DAG和matplotlib来绘制和保存映射。

pip install networkx matplotlib

您可以将映射添加到 inputList 变量。只需确保将其作为字符元组列表提供即可。输出将是与脚本位于同一目录中的 g2.png 文件

import networkx as nx
from numpy import add

inputList = [('a', 'b'), ('b', 'c'), ('e', 'f'), ('d', 'e'), ('c', 'f')]
invertPairs =[]
for x,y in inputList:
    invertPairs.append((y,x))

g2 = nx.DiGraph()
g2.add_edges_from(invertPairs)
plt.tight_layout()
nx.draw_networkx(g2, arrows=True)
plt.savefig("g2.png", format="PNG")
plt.clf()

输出

【讨论】:

  • 嘿@TharunK 感谢您的建议。但是在这里我看不到我正在打印路径
  • @MadhuraMhatre,我现在添加了映射图,请检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 2010-09-26
相关资源
最近更新 更多