首页 > 解决方案 > Python for 循环:循环分层数据

问题描述

我想分析具有以下结构的数据:

parent transaction

     child transaction A     
                  child transaction AA                       
                  child transaction AB
                  child transaction AC

     child transaction B
                  child transaction BA
                  child transaction BB
                  child transaction BC

在这种结构中,子事务(例如子事务 AA)也可能有子事务,我想尽可能多地降低深度,理想情况下甚至通过变量定义最大深度(在变量 depth_level 下方的代码中) 我怎样才能用 for 循环做到这一点?我目前的问题是在完成树的一个分支后停止执行(例如子事务 A)

我的代码目前的结构如下:

start_address=callAddress('bc1qn3gwc49e02kkd2t8svpcmg5hlvtaacvl79wae0')
transaction_targets=analyseTransaction(start_address)
for j in transaction_targets:
    result=callAddress(j)
    inner_transaction_targets=analyseTransaction(result)
    compileAddresses(compiled_receiver_addresses,inner_transaction_targets)
    for i in inner_transaction_targets:
        result=callAddress(i)
        inner_out_addr=analyseTransaction(result)
        compileAddresses(compiled_receiver_addresses,inner_out_addr)
        depth_level=depth_level+1
        print(depth_level)
        if depth_level>50:
            print('Maximum depth reached.')
            break

“analyzeTransaction”函数返回一个交易列表,即上面概述中的子交易。函数“compileAddresses”将所有记录的交易地址收集在一个列表中。我希望循环向下执行直到 x 的深度(由变量“depth_level”标识),然后转到下一个分支(即子事务 B)。

任何想法我做错了什么?

标签: pythonlistloopsfor-loop

解决方案


您无法使用固定的循环控件(例如for. while如果您正在从列表中加载(也许还卸载)信息,您可以使用一些方法。不过,自然而然的方法是使用递归调用来处理遇到的每一级结构,并使用状态参数来控制深度。

就像是:

def traverse(target, depth):
    result=callAddress(target)
    inner_transaction_targets=analyseTransaction(result)
    compileAddresses(compiled_receiver_addresses,inner_transaction_targets)
    if depth > 0:
        for inner in inner_transaction_targets:
            traverse(inner, depth-1)
    else:
        pass  # not sure what you want to do at max depth; just leave it?


for j in transaction_targets:
    traverse(j,max_depth)

推荐阅读