0

I have 30 variables with the pattern aod7039, aod7040, ...., aod7068. I want to do the same operation (i.e. calculate the mean over an axis) for all these variables and overwrite the original variables. Up to now I wrote 30 times the same line, and wondered if there isn't maybe an shorter and easier way to do this? I am gradeful for every idea!

7
  • 1
    You could combine all variable in a dictionary, which is iterable. Commented Mar 19, 2018 at 9:03
  • you could also use eval but keep that in mind eval is evil Commented Mar 19, 2018 at 9:06
  • 2
    Take a step back. Why do you have 30 similar variables? Is this not a misrepresentation of an array? Commented Mar 19, 2018 at 9:09
  • The number at the end of 'aod' is the year, and I want to do a time series over the 30 years. And unfortunately, there are 30 files, so I need to read in each variable separately from each file and then modify them a bit. Commented Mar 19, 2018 at 9:15
  • No you don't; you need to read in each file and then append to the same list or dict. No need for 39 variables. Commented Mar 19, 2018 at 9:16

5 Answers 5

2

Firstly, don't use 30 variables, use a list aod[] Secondly, use

for i in range(7039, 7069):
    aod[i] = yourFunction(aod[i])

to override existing list

Sign up to request clarification or add additional context in comments.

Comments

2

This will get you all values of variables that start with 'aod'

values = [v for k,v in globals() if k.startswith('aod')]

But having 30 variables smells bad.

Comments

1

If I understand your question right, you just want to iterate over those variables?

If so you could keep references on some list/dictionary and then iterate/update this way.

List = []
List.append(aod7039)
for item in List:
    #do something

Comments

1

I have 30 variables with the pattern aod7039, aod7040, ...., aod7068

Then you have a design problem - you should have a list or dict instead. Replace all those variables with either a list or dict (or collections.OrderedDict if you need key access while preserving insertion order) and then it's only a matter of iterating over your container, ie

# with a list:
for index, item in enumerate(yourlist):
    yourlist[index] = do_something_with(item)

# with a dict or OrderedDict:
for key, item in enumerate(yourdict):
    yourdic[key] = do_something_with(item)

Comments

0

store your 30 variables in a list and use map to tackle it without any loop:

varlist=[aod7039, aod7040, ...., aod7068]
result=list(map(yourfunction, varlist))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.