python - 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)。
任何想法我做错了什么?
解决方案
您无法使用固定的循环控件(例如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)
推荐阅读
- sql - 在 SQL 中选择单行的最快方法是什么?(SQL 服务器)
- osmnx - OSMnx:如何从 GeoSeries 获取 OSMnx 统计信息
- javascript - 如何让页脚在 DOM 的第三页开始
- java - HTTPServletResponse 和 ResponseEntity(Spring) 之间的区别?
- image - 离子 - 将图像转换为灰度
- database - Laravel 项目的安全措施(被盗数据库)
- button - VSCode:似乎找不到运行按钮来运行 Javascript 代码
- modelica - 在 modelica 中,Electrical.Analog.Basic.Resistor 的 Heatport 是否仅定义为输出?如果是,如何?
- r - 如果它在距离 1 的 13 个数字的序列内,请继续观察
- python - TypeError: url_for() 接受 1 个位置参数,但给出了 2 个