首页 > 解决方案 > 在主脚本中创建列表,在其他脚本中生成内容,返回主脚本

问题描述

在我的项目中,我想协调从各种数据库中检索到的选定数据并打印出差异。我

  1. 创建一个包含要协调的数据集的列表(dataset1、dataset2、dataset3)
  2. 创建一个列表字典,在其中存储每个数据库的输出(即 list_db1、list_db2、list_db3)
  3. 开始循环,其中对于每个数据集调用 n 个数据库(从外部文件读取 sql 查询)
  4. 修改数据库返回(格式也有质的变化)
  5. 在返回的数据中做一些集合操作
  6. 打印出差异
  7. 清除字典中的列表并转到下一个数据集

我想将第 4 步从主脚本移到外面,以实现更好的可维护性。对于数据集 A,我想以 x_A 方式从数据库 X 修改数据,以 y_A 方式从数据库 Y 修改数据,以 z_A 方式从数据库 Z 修改数据。对于数据集 B,我只想以 z_B 方式修改数据库 Z 中的数据。

修改数据库返回的函数目前是主脚本的一部分,并且是一个有点复杂的 if-then 语句。

def retrieve_db1(dataset):
   ...
   list_db1.append(sql_output)
   ...
def retrieve_db2(dataset):
   ...
   list_db2.append(sql_output)
   ...
def retrieve_db3(dataset):
   ...
   list_db3.append(sql_output)
   ...

def myfunction(arg1,arg2):
     if arg1 == 'dataset1':
       if arg2 == 'list_db1':
          list_db1.append('x')
       elif arg2 == 'list_db3':
          list_db2.append('y')
       else:
          None 

    elif arg1 == 'dataset2':
       if arg2 == 'list_db3':
          list_db3.append('z')
       else:
          None
    ...
    return arg2

datasets = ['dataset1','dataset2','dataset3']
for d in datasets:
   mydict = {'list_db1':[],'list_db2':[],'list_db3':[]}

   retrieve_db1(d)
   myfunction(d,list_db1)
   retrieve_db2(d)
   myfunction(d,list_db2)
   retrieve_db3(d)       
   myfunction(d,list_db3)

   #... merge list_db1 and list_db2, find differences against list_db3, print out etc.

如您所见,函数本身是一个依赖于两个参数的决策树。是否可以仅在单独的文件(脚本)中维护带有决策树的部分代码?

import other_script

def my_function(arg1,arg2):
    ...
    other_script(arg1,arg2)
    ...

树非常复杂,这有助于维护两个脚本。我不确定如何确保在运行 other_script 时修改使用主脚本创建的列表,即当我返回主脚本时数据仍然存在。

标签: pythonlistfunctiondecision-treeexternal-script

解决方案


推荐阅读