2

我有下表,我读入了一个数据框:

n,next_n
1,2
1,3
1,6
2,4
2,8
3,5
3,9
4,7
9,10

我的递归函数应该从最后返回多个数字列表。
例如,如果我选择查看与 9 关联的所有值,我应该得到一个显示为 [9,10] 的列表。
另一个例子:
4 应该产生 [4,7]

3 产生两个列表
[3,5]
[3,9,10]

def 递归数(df,n):
    索引 = 列表()
    
    索引.附加(n)

    x = df[df['n'] == n].next_n

    如果 len(x) > 0:
        对于 df[df['n'] == n].next_n 中的 p1:
            指数 = 指数 + 递归数(df,p1)

    elif len(x) == 0: #Base case - 没有其他值        
        打印(索引)
    
    回报指数

当我运行 recursivenum(df,1)

我得到
[7]
[8]
[5]
[10]
[6]
[1, 2, 4, 7, 8, 3, 5, 9, 10, 6]

与我期望看到的相比,这算不了什么。


我希望看到五个列表: [1,2,4,7]
[1,2,8]
[1,3,5]
[1,3,9,10]
[1,6]

有人可以指出我正确的方向?
4

2 回答 2

1

这更像是一个网络问题,您想创建有向图,然后从根 (1) 到叶(任何级别为 0 的值)

import networkx as nx
G=nx.from_pandas_edgelist(df,source='n',target='next_n', edge_attr=None, create_using=nx.DiGraph())
paths=[]
for node in G:
      if G.out_degree(node)==0: #it's a leaf
          paths.append(nx.shortest_path(G, 1, node))
          
paths
Out[42]: [[1, 6], [1, 2, 8], [1, 3, 5], [1, 2, 4, 7], [1, 3, 9, 10]]
于 2020-08-09T22:01:00.057 回答
0

如果数组由元组组成,请尝试使用 for 循环。

def recursivenum(df,n):
    indices = list()
    
    for x,y in df:
        if x == n:
            indices.append([x,y])
    
    return indices

于 2020-08-09T21:40:14.250 回答