首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >要控制要执行的代码块比在Python中使用if- using语句更好吗?

要控制要执行的代码块比在Python中使用if- using语句更好吗?
EN

Stack Overflow用户
提问于 2018-12-06 16:41:26
回答 1查看 20关注 0票数 0

我主要从事数据科学/分析工作。通常,我需要测试带有和不带随机次抽样的代码(如果原始数据太大),有时显示或隐藏结果,这取决于我是在测试代码还是生成最终结果,以及在.csv中保存最终结果/df等等。

我一直在使用这种策略,即在代码的开头创建一个称为“控制面板”的部分,并在其中设置了许多“开关”等以及用户定义的参数,如下所示

代码语言:javascript
复制
# Control panel
save_file_switch = False # WARNING: will overwrite existing when == True
edge_date_inclusion = True # whether to include the last date in the range of inclusion criteria
testing_printout_switch = False
result_printout_switch = True
df_subsampling_switch = False # WARNING: make to sure turn off for final results
df_subsampling_n = 15000
random_seed = 888

稍后在我的代码中,要打开或关闭的代码块将由开关的值决定。

代码语言:javascript
复制
if testing_printout_switch == True:
    print (df_results) # print some results

到目前为止,我发现它是一种有用的组织工具,但我不知道是否有更好和更多的pythonic方法来解决这个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-06 16:48:09

我会将所有的标志、开关和变量存储在字典中。

代码语言:javascript
复制
control_panel = {
  'save_file_switch': False,
  'edge_date_inclusion': True,
  'testing_printout_switch': False,
  'result_printout_switch': True,
  'df_subsampling_switch': False
  'df_subsampling_n': 15000
  'random_seed': 888
}

if control_panel['testing_printout_switch']:
    print(df_results)

虽然不完全确定这在多大程度上是"Pythonic“,但它为您提供了一个集中存储您的价值观的地方,同时又保持了它们的独特性和独特性。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53655960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档