0

前任。让我们考虑一下,我有一个清单,

list_var = ['sales_qty' , 'returns_qty' , 'net_sales_qty' , 'sales_amt' , 'returns_amt' ,'product_discount_amt' , 'product_net_amt' ,'product_cost_amt' , 'gross_sales_amt' , 'supplier_disc_amt' , 'category_disc_amt' , 'topup_disc_amt' , 'value_at_cost']

从这个列表元素中,我想像list在内存中一样初始化这些元素,所以我可以append, extend对这些元素使用方法。

如下,

#Need these variable in memory..
sales_qty = [], returns_qty  = [], net_sales_qty = [] ... value_at_cost = []

#list operation on variable..
sales_qty.append(5)

有什么简单的方法可以做到这一点,所以我可以轻松地删除元素或在列表中添加元素?

4

3 回答 3

5

您可以基于list_var.

list_var = ['sales_qty' , 'returns_qty' , 'net_sales_qty' , 'sales_amt' , 'returns_amt' ,'product_discount_amt' , 'product_net_amt' ,'product_cost_amt' , 'gross_sales_amt' , 'supplier_disc_amt' , 'category_disc_amt' , 'topup_disc_amt' , 'value_at_cost']

list_dic = {k: [] for k in list_var}

现在可以通过list_dicdict 访问您的列表:

list_dic['sales_qty'].append(123)
list_dic['category_disc_amt'].append('abc')

如果您使用的 python 版本不支持字典推导(python 2.6 或更低版本),则可以使用列表推导(正如 DSM 在他的评论中解释的那样):

list_dic = dict((k, []) for k in list_var)
于 2013-01-29T12:25:24.320 回答
2

vars如果您从全局范围调用,请使用。否则,使用globals.

list_var = ['sales_qty' , 'returns_qty' , 'net_sales_qty' , 'sales_amt' , 'returns_amt' ,'product_discount_amt' , 'product_net_amt' ,'product_cost_amt' , 'gross_sales_amt' , 'supplier_disc_amt' , 'category_disc_amt' , 'topup_disc_amt' , 'value_at_cost']

for item in list_var:
    vars()[item] = []

sales_qty.append(1)
sales_qty.append(3)
returns_qty.append(2)

print "Outside..."
print sales_qty
print returns_qty


def foo():
    global sales_qty

    sales_qty.append(4)

    print "Inside foo..."
    print sales_qty
    print returns_qty

    # This works if you want the whole thing inside a function
    print "Variable from inside foo..."
    globals()["new_var"] = []
    new_var.append(5)
    print new_var

foo()

print "Outside again..."
print sales_qty
print returns_qty

输出:

>>> 
Outside...
[1, 3]
[2]
Inside foo...
[1, 3, 4]
[2]
Variable from inside foo...
[5]
Outside again...
[1, 3, 4]
[2]
>>> 
于 2013-01-29T12:30:53.520 回答
0

你的意思是这样的:

list_var = [ 'abc', 'cde', 'fgh' ]

dict_var = dict()
for x in list_var:
    dict_var[x] = []

dict_var['abc'].append(5)
于 2013-01-29T12:25:11.043 回答