我有一个变量名列表和一个酸洗对象名称列表:
pickle_var_names = object1, object2 # both empty, which throws an error
pickle_names = ['object1', 'object2']
我希望将pickle_names
中调用的泡菜分别加载到pickle_var_names
中:
for pickle_var_name,pickle_name in zip(pickle_var_names,pickle_names):
with open(pickle_name,'r') as pickle_fp:
pickle_var_name = cPickle.load(pickle_fp)
如何将变量列表初始化为None
以允许稍后分配?
答案 0 :(得分:1)
列表按位置索引,而不是按名称索引,因此您可以执行此操作:
picklevars = []
picklenames = ['object1', 'object2']
for picklename in picklenames:
with open(pickle_name, 'r') as pickle_fp:
picklevars.append(cPickle.load(pickle_fp))
或者,如果您能够使用字典而不是列表:
picklevars = {}
picklenames = ['object1', 'object2']
for picklename in picklenames:
with open(pickle_name, 'r') as pickle_fp:
picklevars[picklename] = cPickle.load(pickle_fp)