This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.
for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])
I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.
Thanks in advance
You are trying to do this:
test1 = something
test2 = something else
for i in range(1,2):
print('test' + str(i))
however, that won't work because strings cannot be used as variable names. You can cheat somewhat by using locals(), which creates a dictionary of local variables:
test1 = something
test2 = something else
for i in range(1,2):
print(locals()['test' + str(i)])
but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.
d = {'test1': something,
'test2': something else}
for i in range(1,2):
print(d['test' + str(i)])
# or even better
tests = [something, something else]
for test in tests:
print(test)
# even better, what you're trying to do is this:
for i, test in enumerate(tests):
period_writer.writerow([i+1, max(test)])
This makes it much clearer that the variables belong together and will run faster to boot.
Related
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 months ago.
Is there any way that I can automatically create new variables based on how many items I have in a Python list?
For instance, if I have a variable like this:
var = (json.loads(requests.get(list[0])).text)
Is it possible to automatically create additional variables like this, depending on the length of my list? I'd like to avoid manually writing out all my variables. Let's say my list has 4 items (length = 4).
var = (json.loads(requests.get(list[0])).text)
var1 = (json.loads(requests.get(list[1])).text)
var2 = (json.loads(requests.get(list[2])).text)
var3 = (json.loads(requests.get(list[3])).text)
I would appreciate any help. Thank you.
Why don't you try to use a dict to handle this problem?
vars = {f'var{i}': json.loads(requests.get(yourlist[i])).text for i in range(len(yourlist))}
You can access your variables: vars['var1'] or vars.get('var1')
In general, creating new variables during the program execution isn't a good ideia.
The direct answer to your question is to add the values in the global dictionary. It can be done with globals, eval, exec. I don't recommend to do that because if you have a long list which change size then you have to remember how many elements you have.
Here an abstraction of the problem:
var_str_pattern = 'var{}'
val = ['smt', 'else']
for i, v in enumerate(val, start=1):
globals()[var_str_pattern.format(i)] = v
print(var1)
#smt
print(var2)
#else
For the specific question:
n = 3
var_str_pattern = 'var'
for i in range(1, n+1):
globals()[f'{var_str_pattern}{i}'] = json.loads(requests.get(list[i])).text
print(var1)
print(var2)
print(var3)
You should use a dictionary approach as in the answer of Riqq.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
NOTE: Please read till the end, I don't want dictionaries.
For example, I have the global variable called var1 and I have the following:
i = 0
for i in range(0, 20):
var1 = i
i += 1
I want to create a new variable called var2 and store the value from the second iteration into that, instead of the initial var1 and so on for every iteration.
I also don't want to store it in some list var and use var[i] for every iteration.
I want the variable names to logically be named for every iteration.
Is there a direct solution or is there any way I can make a variable with the contents of a string?
The main intent of the question is to know if I can generate a new variable for every iteration with naming that has some logic behind it, instead of using lists.
Also, I do not want to define dictionaries as dictionaries have definite sizes and cannot flexibly expand themselves.
You can use exec
The exec() method executes the dynamically created program, which is either a string or a code object.
for i in range(0, 20):
exec("%s = %d" % (f"var{i+1}",i))
print(var1)
print(var2)
print(var3)
print(var4)
print(var18)
print(var19)
0
1
2
3
17
18
This question already has answers here:
Getting one value from a tuple
(3 answers)
Closed 2 years ago.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(a_tuple(variable1))
Is there a way I can pass a specific value from a tuple into a function? This is a terrible example, but all I need to know is if I can pass variable1 from the tuple into the function, I understand in this instance I could just pass in variable 1, but its for more complicated functions that will get its data from a tuple, and I don't like the look of that many variables, too messy.
variable1 = 1
variable2 = 2
a_tuple = (variable1, variable2)
def my_function(a):
pass
my_function(*a_tuple)
This code would obviously provide an error as it unpacks the tuple and inserts 2 variables, to make this work in my program I would need a way to pass either variable1 or variable2 into the function. My question is can I define exactly which items from a tuple are passed into the function when calling the function? Latest version of Python if it matters.
P.S. I wrote print("hello world") for the first time 7 days ago, this is my first language and my first question I couldn't find an answer to. Go easy on me, and thank you for your time.
In the code you provided you don't have a tuple you have a list. But it is still pretty much the same.
In your example lets say that you wanted to pass the first variable you would do it like this:
my_function(a_tuple[0])
If you don't understand why there is a zero here and how does this work I highly suggest learning about lists before functions.
You just need to access individual elements of the tuple, using index notation:
my_function(a_tuple[0])
or
my_function(a_tuple[1])
You could, if you wanted, write a new function which takes a tuple and an index, and calls my_function with the appropriate element:
def my_other_function(tuple, index):
return my_function(tuple[index])
But I don't see how there would be much gain in doing that.
you can index a tuple or use the index method.
def my_function(a):
pass
my_function(a_tuple[0])
if you want to get the index of a value use the index() method
a_tuple.index(variable1) #this will return 0
This question already has answers here:
How do I create variable variables?
(17 answers)
How can you dynamically create variables? [duplicate]
(8 answers)
Closed 3 years ago.
I want to initialize and assign variables in a single loop, like I used to be able to in Stata, using a static element + an iterable element. I've edited the examples for clarity. The reason I want this is because it allows me to perform an operation on variables that have different contents in one loop. I can't just print a fixed string followed by something else.
Kind of like (pseudocode):
for each `x' in 1/10:
print var`x'
And this would print, not "var1, var2, var3, etc." but the actual values of contained within var1, var2, and var3, so long as they had been previously defined.
Or you could even do things like this, again more pseudocode:
foreach `x' in 1/10:
thing`x' = `x'
This would both initialize the variable and put a value into it, in one step, in the same loop. Is there a way to do this sort of thing in python, or is it, as I've read elsewhere, "unpythonlike" and more or less forbidden?
I don't have a pressing problem at the moment. In the worst case, I can just link together long chains of print statements. But it bothers me that I can't just print the results I want by calling a bunch of serial variables in a loop. I've tried variations of
Books1 = Dogs
Books2 = Cats
Books3 = Lemurs
for x in range(10):
for y in [books]:
print y, x
But that just outputs something like
Books1
Books2
Books3
...
When I want:
Dogs
Cats
Lemurs
Would appreciate if someone could point me the right direction!
You dont need to iterate over books:
for idx in range(10):
print("Author's name", idx)
>> Author's name 0
>> Author's name 1
>> Author's name 2
>> Author's name 3
>> Author's name 4
>> Author's name 5
>> Author's name 6
>> Author's name 7
>> Author's name 8
>> Author's name 9
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
Here is what I would like to be able to do:
I have a file called functions, with lots of functions. The functions are all essentially the same, functionally speaking (i.e., they are all of the form: pandas.Dataframe -> pandas.Dataframe). Obviously, they do different things to the Dataframe, so in that sense they are different.
I'd like to be able to pass my main function a list of strings, which would be the actual function names in the module, and have my program translate the strings into function calls.
So, basically, instead of:
functions = [module.functionA, module.functionB, module.functionC]
x = g(functions)
print(x)
> 'magical happiness'
I would have:
function_strings = ['functionA','functionB','functionC']
functions = interpret_strings_as_function_calls(module,function_strings)
x = g(functions)
print(x)
> 'magical happiness'
Is there a way to do this? Or do I need to write a function in the module that matches each string with it's corresponding function? i.e.:
def interpret_strings(function_string):
if function_string == 'functionA':
return module.functionA
elif function_string == 'functionB':
return module.functionB
etc.
(or in a switch statement, or whatever)
You can use getattr(module, function_string).