在python中最小化列表变量块

2024-10-02 00:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在下面列出了大量变量。有没有一种方法可以同时将一组变量名指定为列表?用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 = [] 

Tags: and方法列表forkeepingamountlonglist
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']

如果确实希望避免单独声明一组列表,则始终可以使用defaultdict作为空列表的工厂:

from collections import defaultdict

all_my_lists = defaultdict(list)

现在你已经拥有了所有你想要的空列表。您可以按名称访问它们,并对空列表执行任何操作:

all_my_lists['Amount'].append(amount)

一旦创建了列表,它就会持续存在defaultdict只是在您第一次使用任何给定的密钥时为您创建一个空列表

这种方法的问题是,如果你在其中一个键上有一个输入错误,很容易漏掉,并且会产生不明显的错误。命名变量更难搞乱,因为如果键入一个,可能会导致明显的运行时错误(如果使用typechecker,甚至在运行程序之前都会出错)

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

相关问题 更多 >

    热门问题