【问题标题】:Minimizing a chunk of list variables within python在python中最小化一大块列表变量
【发布时间】:2020-12-19 05:50:28
【问题描述】:

我在下面有一大堆列表变量。有没有办法可以一次将一堆变量名分配为列表?用for循环之类的?我愿意接受任何想法:)。

#Keeping track of the General Long and Short Compounding,General Long and Short Non Compounding Values
Amount_list=[]
S_Amount_list= []
L_Amount_list= []
Non_compounding_list = []
S_Non_compounding_list = []
L_Non_compounding_list = []

#Positions
#scatter graph variables
LongPosition = []
LongPosition_x = []
ShortPosition = []
ShortPosition_x = [] 

【问题讨论】:

  • 具体长度是多少?
  • 我应该用重复替换单词长度,刚刚更新了信息
  • 还是不清楚!
  • 你可以做很多事情,但是你应该考虑可读性和可维护性。像你已经拥有的那样定义列表比任何类型的 dict 或循环 IMO 都清晰得多,遇到不知道键是什么的 dict 会导致一些最糟糕的代码维护

标签: python python-3.x list


【解决方案1】:

如果你真的想避免单独声明一堆列表,你总是可以使用defaultdict 作为空列表的工厂:

from collections import defaultdict

all_my_lists = defaultdict(list)

现在您实际上拥有了您可能想要的所有空列表。您可以通过名称访问它们并对空列表执行任何操作:

all_my_lists['Amount'].append(amount)

列表一经创建,就一直存在; defaultdict 只是在您第一次使用任何给定键时为您创建一个空列表。

这种方法的问题在于,如果您在其中一个键中有错字,很容易漏掉,并且会产生不明显的错误。命名变量更难搞砸,因为如果你打错了一个,它可能会导致一个明显的运行时错误(如果你使用类型检查器,它甚至会在你运行程序之前出错)。

但是,如果您在同一范围内有大量列表,那么 可能 意味着您没有以最佳方式对数据进行建模。也许其中一些数据应该在列表列表、字典或管理相关数据块的对象类中。不幸的是,如果不了解应用程序的其余部分,就无法就如何改进数据模型提出建议。

【讨论】:

    【解决方案2】:

    您是否考虑过使用字典?类似的东西

    #Keeping track of the General Long and Short Compounding,General Long and Short Non Compounding Values
    lists = {
        'Amount': []],
        'S_Amount': [],
        'L_Amount': [],
        'Non_compounding': [],
        'S_Non_compounding': [],
        'L_Non_compounding': []
    {
    
    #Positions
    #scatter graph variables
    positions = {
        'LongPosition': [],
        'LongPosition_x': [],
        'ShortPosition': [],
        'ShortPosition_x': []
    }
    

    然后您可以使用类似的方式访问这些值

    amount = lists['Amount']
    

    【讨论】:

      猜你喜欢
      • 2018-08-08
      • 2015-02-28
      • 2018-10-22
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多