我有三张单子:
years = [2013,2014,2015,2016,2017,2018]
GamsVars = ['scen_name','timefile']
settings = ['ScenarioA','s']
我有一个函数用于返回一个与设置完全相同的列表,但在相关条目后面附加了年份:
def AppendYearToSettings(year,GamsVarsIn,SettingsIn):
SettingsOut = SettingsIn
SettingsOut[GamsVarsIn.index('scen_name')] = SettingsIn[GamsVarsIn.index('scen_name')] + "\\" + str(year)
SettingsOut[GamsVarsIn.index('timefile')] = SettingsIn[GamsVarsIn.index('timefile')] + str(year)
return(SettingsOut)
在循环中测试函数时:
for y in years:
ysettings = AppendYearToSettings(y,GamsVars,settings)
print(ysettings)
我的ysettings
是累加的年份:
['ScenarioA\\2013', 's2013']
['ScenarioA\\2013\\2014', 's20132014']
['ScenarioA\\2013\\2014\\2015', 's201320142015']
['ScenarioA\\2013\\2014\\2015\\2016', 's2013201420152016']
['ScenarioA\\2013\\2014\\2015\\2016\\2017', 's20132014201520162017']
['ScenarioA\\2013\\2014\\2015\\2016\\2017\\2018', 's201320142015201620172018']
我尝试过显式地阻止修改设置(原始设置),但似乎我的函数正在修改设置。你知道吗
造成这个问题的原因是什么?你知道吗
在执行
SettingsOut = SettingsIn
时,您只创建了对SettingsIn
引用的对象的另一个引用。如果要复制列表,可以执行以下操作:或者,您可以使用copy.deepcopy(您需要导入
copy
才能使用它)。只有当列表中的元素本身是引用,并且您还希望创建对象的新副本时,才需要使用此选项。请看下面johny的评论。你知道吗看看这个:
所以你的函数可以是这样的:
输出:
有点误入歧途,但你应该看看PEP style guide for function naming;-)它说:
相关问题 更多 >
编程相关推荐