Emily
Emily

Reputation: 13

Calling a variable name as a string in for loop function

I have a series of variables that appear like this:

halpha = 6562.8
hbeta = 4861
ca1 =  8498
ca2 = 8542
ca3 =  8662
o3 = 5008.240

I have a plotting function here:

def abslines(molecule,title):
    plt.axvline(molecule, color = "r", label=title)
    plt.text(molecule-100, 40, title,rotation=90,fontsize=20)

And it works when input looks like:

abslines(he,"he")

And the function works just fine, but I don't want to have a ton of lines where I just call the function for each of the variables, so I put the variables in an array, and in a for loop I call the function. How do I call the variable name, which is the second input of the abslines function?

absarray = [halpha,hbeta,ca1,ca2,ca3,o3,na,mg,he]
for i in absarray:
    abslines(i,"i")

Upvotes: 1

Views: 1357

Answers (4)

Walter Tross
Walter Tross

Reputation: 12624

If instead of variables you use a dictionary, you can simply index the dictionary with the name of each item. Like:

abs = {
    # optional init - may or may not be useful:
    "halpha": 0,
    "hbeta": 0,
    ...
}
...
abs["halpha"] = ...
...
for name in abs:
    abslines(abs[name], name)

Upvotes: 1

Easiest may be to use python's built-in map() function:

>>> map(lambda n: abslines(n, 'i'), absarray)

(6562.8, 'i')
(4861, 'i')
(8498, 'i')
(8542, 'i')
(8662, 'i')
(5008.24, 'i')

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51653

Use a dict, skip the variables that just hold what - molecule weights?

from  matplotlib import pyplot as plt

data = { "halpha" : 6562.8, "hbeta" : 4861,   "ca1" :  8498,
         "ca2"    : 8542,   "ca3"   :  8662,  "o3"  : 5008.240,  }

def abslines(molecule,title):
    plt.axvline(molecule, color = "r", label=title)
    plt.text(molecule-100, 0.40, title,rotation=90,fontsize=20) # fix  y

for b,a in data.items():
    abslines(a,b)

plt.show()

to get

pic

Upvotes: 0

MooingRawr
MooingRawr

Reputation: 4991

There are ways to inspect the script's variable name but that seems to be over kill here since you can construct a dictionary with it's name and the "function" and just call it. Use the key for the name you want, and the value to be the function:

absarray = {"halpha":halpha,"hbeta":hbeta,"ca1":ca1,"ca2":ca2,"ca3":ca3,"o3":o3,"na":na,"mg":mg,"he":he}

for k,v in absarray.items():
    abslines(v,k)

Upvotes: 2

Related Questions