我正在尝试组合一个具有“级别”概念的工具。每个“级别”都有一组变量来支持我想要实现的特定于每个级别的活动。
我写了一个硬编码的版本(在一定程度上),但它仅限于我硬编码的级别数。让我感到震惊的是,必须有一种更巧妙的方式来编写这个函数,这样才能动态生成关卡变量:
def levelVarsGetter(level):
if level == 1:
levelDict = {'URLRegEx':baseDict['L1Regex'], 'titleRegEx':baseDict['L1TitleRegex'], 'buildPortion':baseDict['L1buildPortion'], 'levelParser':'level_1'}
elif level ==2:
levelDict = {'URLRegEx':baseDict['L2Regex'], 'titleRegEx':baseDict['L2TitleRegex'], 'buildPortion':baseDict['L2buildPortion'], 'levelParser':'level_2'}
elif level ==3:
levelDict = {'URLRegEx':baseDict['L3Regex'], 'titleRegEx':baseDict['L3TitleRegex'], 'buildPortion':baseDict['L3buildPortion'], 'levelParser':'level_3'}
elif level ==4:
levelDict = {'URLRegEx':baseDict['L4Regex'], 'titleRegEx':baseDict['L4TitleRegex'], 'buildPortion':baseDict['L4buildPortion'], 'levelParser':'level_4'}
elif level ==5:
levelDict = {'URLRegEx':baseDict['L5Regex'], 'titleRegEx':baseDict['L5TitleRegex'], 'buildPortion':baseDict['L5buildPortion'], 'levelParser':'level_5'}
return levelDict
dict 中的所有变量都是在初始化函数中手动输入的。如果需要,可以更改标签。
对于上下文,引用代码:
for x in xrange (1, baseDict['numberOfLevels']+1):
links=[]
levelDict= levelVarsGetter(x)
URLRegEx = levelDict['URLRegEx']
titleRegEx = levelDict['titleRegEx']
buildPortion = levelDict['buildPortion']
level = levelDict['levelParser']
go = siteParser()