Question

So if I have code that takes in some lists, reorders them and creates differently named and ordered list etc etc like so:

for names in twentyandovermenfreestyle:
    nameid = twentyandovermenfreestyle.index(names)

try:
    breastid = twentyandovermenbreastroke.index(names)
except ValueError:
        twentyandovermenBreastroke.append(names)
        breastid = twentyandovermenBreastroke.index(names)
        twentyandovermenBreastroke.append(1000)
    twentyandovermen_Breast.append(twenyandovermenbreastroke[breastid])

Is there a way I could bind the whole thing in a function, and pass the arguments to build the string names of the lists? something like:

def strokesort(agegroup,gender):

    for names in ***agegroup + gender*** +freestyle: # ie it build the string name of the code above?
        nameid = ***agegroup + gender*** + freestyle.index(names)

    try:
        breastid = ***agegroup + gender*** + breastroke.index(names)
    except ValueError:
        ***agegroup + gender*** + Breastroke.append(names)
        breastid = ***agegroup + gender*** + Breastroke[0].index(names)
        ***agegroup + gender*** + Breastroke.append(1000)
    ***agegroup + gender*** + _Breast.append(***agegroup + gender*** + breastroke[breastid])

I hope that makes sense. I'm going to be reusing this function a bunch, and I'd rather not have to explicitly type out each list name within the parameters, and I do use a consistent naming approach, so I figure there's got to be a way to construct strings that then "are" the dictionary names?

Was it helpful?

Solution

First of all, if you make this a function the local names don't need to be specific:

def strokesort(agegrp, gender):
    lst = []
    lst.append(whatever)
    return lst

Then you can assign some meaningful name to the list when the function returns:

twentyandovermen_breast = strokesort('twentyandover', 'men')

Secondly, dynamic variable names are rarely the right answer. Why not have a dictionary-based structure:

{'twentyandover': {'men': [...], ...}, ...}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top