我有一个内部循环和一个外部循环(数据库中的记录)。外循环 (json) 基于几个字段创建过滤器(例如:begin/end => 0 : 0.5 >>> ID 114 到 159)。
桌子 :
ID begin end status FK1_field FK2_field FK3_field FK4_field FK5_field report_id
114 0 0.5 1 NULL 13 8 142 44 1
115 0 0.5 1 NULL 13 8 61 45 1
158 0 0.5 1 NULL 13 8 142 45 1
159 0 0.5 1 NULL 13 8 61 44 1
116 0.5 1.5 1 NULL 13 8 142 45 1
117 0.5 1.5 1 NULL 13 8 131 45 1
118 1.5 2.5 1 NULL 13 8 142 45 1
结果在内部循环上循环(例如:4条记录/行(*))。
但是,当我退出内部循环时,必须在外部循环上循环4次(*),以获得ID 116(以及过滤器的开始/结束)=> 0.5:1.5。
事实上,我只能循环内部循环并使用“if”进行相同的几次测试。但是我认为过滤更加优雅。现在,我认为退出内循环时循环是愚蠢的。
编码 :
highways = tools_cronjob.getAPI(API_URL + action, headers)
for highway in highways:
print('>>>>> Highway : %s ' % highway['name'])
# all the prpk, same values like the table
prpk_by_highway = tools_cronjob.getAPI(API_URL + actions_api['prpk_by_highway'] + "%s" % (highway['id']), headers)
# get all prpk by highway
for prpk in prpk_by_highway:
filtered_by_begin_end = [pr_pk for pr_pk in prpk_by_highway if pr_pk['begin'] == prpk['begin']]
# each couple of prpk 'begin' and 'end'
for filter_prpk in filtered_prpk_by_begin_end:
# some stuff
print (filter_prpk)
# when I exit, for eg, I must continue looping (prpk in prpk_by_highway) starting the couple begin/end : 0.5 : 1.5
所以第一个循环是 4 条记录,第二个是 2 个,第三个是 1 个。
最好的解决方案是什么?
相关分类