[英]Python - Initializing List variable from List elements
Ex. 例如 Lets consider, I have a list,
考虑一下,我有一个清单,
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']
from this list element, i want to init these elements as list
in the memory, so i could use append, extend
method for these elements. 从这个列表元素开始,我想将这些元素初始化为内存中的
list
,因此我可以对这些元素使用append, extend
方法。
As follow, 如下,
#Need these variable in memory..
sales_qty = [], returns_qty = [], net_sales_qty = [] ... value_at_cost = []
#list operation on variable..
sales_qty.append(5)
Is there any simple way to do that, so i could remove element or add element in list easily? 有没有简单的方法可以做到这一点,所以我可以轻松地删除元素或在列表中添加元素?
You could create a dictionary of lists based on list_var
. 您可以基于
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}
Now can access your lists through the list_dic
dict: 现在可以通过
list_dic
dict访问您的列表:
list_dic['sales_qty'].append(123)
list_dic['category_disc_amt'].append('abc')
If you're using a python version that does not support dict comprehensions (python 2.6 or lower), you can use a list comprehension instead (as DSM explained in his comment): 如果您使用的是不支持dict理解的python版本(python 2.6或更低版本),则可以改用列表理解(如DSM在其评论中所述):
list_dic = dict((k, []) for k in list_var)
Use vars
if you are invoking from global scope. 如果要从全局范围调用,请使用
vars
。 Otherwise, use globals
. 否则,请使用
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
Output: 输出:
>>>
Outside...
[1, 3]
[2]
Inside foo...
[1, 3, 4]
[2]
Variable from inside foo...
[5]
Outside again...
[1, 3, 4]
[2]
>>>
You mean something like this: 您的意思是这样的:
list_var = [ 'abc', 'cde', 'fgh' ]
dict_var = dict()
for x in list_var:
dict_var[x] = []
dict_var['abc'].append(5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.