This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I have two lists in python
targetvariables = ['a','b','c']
featurevariables = ['d','e','f']
I would like to create three lists such as the following:
a_model = ['a','d','e','f']
b_model = ['b','d','e','f']
c_model = ['c','d','e','f']
I have about 15 target variables and 100+ feature variables so is there a way to do this in a loop of some kind? I tried but I couldnt work out how to assign a list name from a changing variable:
for idx,target in enumerate(targetvariables):
target +'_model' = targetvariables[idx] + featurevariables
SyntaxError: can't assign to operator
The end goal is to test machine learning models and to make things easier I would like to simply call:
df[[a_model]]
to then use in the ML process.
Short answer: DO NOT DO THIS!
By doing this you're corrupting the global namespace and that's not recommended. If you really need to do this, this is how:
for target_var in targetvariables:
# access the global namespace and modify it
globals()[f'{target_var}_model'] = [target_var] + featurevariables
Alternative #1
Instead of storing the lists in variables, store them in a container, for example, a dict:
models = {} # create an empty dict
for target_var in targetvariables:
# the same as the last example but with 'models' instead of 'globals()'
models[f'{target_var}_model'] = [target_var] + featurevariables
Then access the lists like so:
>>> models['a_model']
['a','d','e','f']
You can also easly change the code so that the keys of the dict would be the variable name itself, without "_model".
Alternative #2
Instead of storing the lists, create them on the fly with a function:
def get_model(target_var):
return [target_var] + featurevariables
Then access the lists like so:
>>> get_model('a')
['a','d','e','f']
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am attempting to set the value of a variable to incrementally equal that of another variable based on the iteration of the loop I am on.
I have the following code:
no_keywords=3
cat_0='Alpha'
cat_1='Bravo'
cat_2='Charlie'
cat_3='Delta'
for _ in range(no_keywords):
keyword1 = exec(f'cat_{_}')
print(keyword1)
However the printed value just returns a NoneType object. I would like the value of Keyword1 to take on the value of the cat_ variable based on the iteration of loop I am on.
Please can somebody help in explaining in what I am doing wrong and help me recitfy?
Thanks,
D
Try this:
no_keywords = 3
cat_0 = 'Alpha'
cat_1 = 'Bravo'
cat_2 = 'Charlie'
cat_3 = 'Delta'
for _ in range(no_keywords):
keyword1 = None
exec(f'keyword1 = cat_{_}')
print(keyword1)
Seems like exec does not return a value, but you can set your variable within the command passed to it.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
d={'a0': [['5021', '5031'], ['4994', '4991', '5042'],
['4992', '4995', '5021', '4994'], ['5037', '5038']],
'a24': [['5009', '5014'], ['5009', '5014'], ['4993', '4998', '5030', '4991']]
}
I have the above dict in python.
I need to make list with the name of it being the names of keys in the dict.
The list with the name of the key should have the items as its corresponding values in dict.
The output should be:
a0=[['5021', '5031'], ['4994', '4991', '5042'],
['4992', '4995', '5021', '4994'], ['5037', '5038']]
a24=[['5009', '5014'], ['5009', '5014'], ['4993', '4998', '5030', '4991']]
Any help is appreciated.
First, rethink if this is really necessary. Dynamically creating variables is confusing and does not occur often. It would be better to avoid this.
However, you can do it like this:
for name, val in d.items():
exec("{}={}".format(name,val))
for key, item in d.items():
print(str(key) + "=" + str(item))
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am having a function in python
def func(dataFrame,country,sex):
varible_name=dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
Now, for example, I call this function
func(dataFrame,'England','M')
I want that variable name be England_M instead of variable_name.
You can't do that in Python.
What you can do instead is store the results under a dictionary with key = England_M for instance.
In your case, you could do the following :
def func(dataFrame,country,sex):
tmp = dataFrame[(dataFrame['land']==country) & (dataFrame['sex']==sex)]
variable_name = "{c}_{s}".format(c=country, s=sex)
return dict(variable_name=tmp)
Now using it :
results = func(dataFrame, "England", "M")
print(results['England_M'])
This question already has answers here:
Access to value of variable with dynamic name
(3 answers)
Closed 6 years ago.
I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.
def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print found_item
Then, I want to use the variable name 'found_item' to call a dictionary of the same name, eg:
print found_item['key_1']
But I get the error, "TypeError: string indices must be integers, not str"
How would I use a string to call a previously defined dictionary that shares the same name?
You can use a variable via its name as string using exec:
dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
Short answer: I don't think you can.
However, if the dictionary explore_items uses the dicts in questions as its keys, this should work.
ETA to clarify:
explore_items = {{dict1}: a, {dict2}:b, {dict3}:c}
random_key= random.choice(explore_items.keys())