函数在不需要时修改输入

2024-10-03 02:44:44 发布

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

我有三张单子:

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']

我尝试过显式地阻止修改设置(原始设置),但似乎我的函数正在修改设置。你知道吗

造成这个问题的原因是什么?你知道吗


Tags: 函数nameindexsettingsyear年份yearsscen
1条回答
网友
1楼 · 发布于 2024-10-03 02:44:44

What is the reason that is causing this problem?

在执行SettingsOut = SettingsIn时,您只创建了对SettingsIn引用的对象的另一个引用。如果要复制列表,可以执行以下操作:

SettingsOut = SettingsIn[:]

或者,您可以使用copy.deepcopy(您需要导入copy才能使用它)。只有当列表中的元素本身是引用,并且您还希望创建对象的新副本时,才需要使用此选项。请看下面johny的评论。你知道吗

SettingsOut = copy.deepcopy(SettingsIn)

看看这个:

>>> l1 = [1, 2, 3, 4, 5]
>>> l2 = l1
>>> l2 is l1
True
>>> id(l1)
24640248
>>> id(l2)
24640248

>>> l2 = l1[:]
>>> l2 is l1
False
>>> id(l2)
24880432
>>> id(l1)
24640248
>>>

所以你的函数可以是这样的:

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)

输出:

['ScenarioA\\2013', 's2013']
['ScenarioA\\2014', 's2014']
['ScenarioA\\2015', 's2015']
['ScenarioA\\2016', 's2016']
['ScenarioA\\2017', 's2017']
['ScenarioA\\2018', 's2018']

有点误入歧途,但你应该看看PEP style guide for function naming;-)它说:

Function Names

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

相关问题 更多 >