I have some dynamic items in dictionary type. I want to unpack some of them into variables. I want to know some methods by using loop.
I have 'self.params = {}' to store basis and weights. Maybe 10 or 20 b and W, which depend on parameters into class. I want to unpack it into 'W1','W2'.....,'b1','b2'.....I have layer number in 'hidden_dims'
I want to realize some functions like follow false code:
for i in range(hidden_dims):
W(i+1) = self.params['W%s'% str(i+1)]
b(i+1) = self.params['b%s'% str(i+1)]
Then I can get some variables like:'W1','W2'...'Wn'(and n = hidden_dims) and 'b1','b2'...'bn'
can it be realized?
You can create variables dynamically using global(). Something like this:
for i in range(1, hidden_dims + 1):
w = 'W' + str(i)
b = 'b' + str(i)
global()[w] = self.params[w]
global()[b] = self.params[b]
Note: It is not advisable to try and create variables dynamically. For your use case, the use of two lists W[] and b[] seems like a much cleaner way to store the values
Related
I am very new to Python, and I'm trying to combine elements from two lists and produce a string from the combination.
My variables are:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
I want output like this in a string:
pairs = "USDAUD,USDCAD,USDEUR"
Thanks a ton in advance for your help.
Why not use a generator expression like this:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
pairs = ','.join(fro[0] + x for x in to)
Note that from is a reserved keyword and is thus not a valid variable name.
Output:
>>>pairs
'USDAUD,USDCAD,USDEUR'
If you were ever curious as to whether something you wish to use as a variable name is a keyword (and thus an illegal variable name) or not, you can always check with something like this:
>>> import keyword
>>> keyword.iskeyword("from")
True
Elizion's answer is nice and succinct, but as a beginner you may want to approach it without using an intermediate/advanced structure like a generator:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
pairs = ""
for word in to:
pairs += fro[0] + word + ","
Removing the trailing comma:
pairs = pairs[:-1]
Elizion is absolutely correct.
If you have list elements varies dynamically, you can use this line:
absolutely pythonic way!!
pair_elem = ','.join('%s%s' % (x, y) for y in to for x in fro)
And conventional way is like, iterate list elems:
for multiple in to:
for single in fro:
pairs = ",".join(single + multiple)
I have a function that takes given initial conditions for a set of variables and puts the result into another global variable. For example, let's say two of these variables is x and y. Note that x and y must be global variables (because it is too messy/inconvenient to be passing large amounts of references between many functions).
x = 1
y = 2
def myFunction():
global x,y,solution
print(x)
< some code that evaluates using a while loop >
solution = <the result from many iterations of the while loop>
I want to see how the result changes given a change in the initial condition of x and y (and other variables). For flexibility and scalability, I want to do something like this:
varSet = {'genericName0':x, 'genericName1':y} # Dict contains all variables that I wish to alter initial conditions for
R = list(range(10))
for r in R:
varSet['genericName0'] = r #This doesn't work the way I want...
myFunction()
Such that the 'print' line in 'myFunction' outputs the values 0,1,2,...,9 on successive calls.
So basically I'm asking how do you map a key to a value, where the value isn't a standard data type (like an int) but is instead a reference to another value? And having done that, how do you reference that value?
If it's not possible to do it the way I intend: What is the best way to change the value of any given variable by changing the name (of the variable that you wish to set) only?
I'm using Python 3.4, so would prefer a solution that works for Python 3.
EDIT: Fixed up minor syntax problems.
EDIT2: I think maybe a clearer way to ask my question is this:
Consider that you have two dictionaries, one which contains round objects and the other contains fruit. Members of one dictionary can also belong to the other (apples are fruit and round). Now consider that you have the key 'apple' in both dictionaries, and the value refers to the number of apples. When updating the number of apples in one set, you want this number to also transfer to the round objects dictionary, under the key 'apple' without manually updating the dictionary yourself. What's the most pythonic way to handle this?
Instead of making x and y global variables with a separate dictionary to refer to them, make the dictionary directly contain "x" and "y" as keys.
varSet = {'x': 1, 'y': 2}
Then, in your code, whenever you want to refer to these parameters, use varSet['x'] and varSet['y']. When you want to update them use varSet['x'] = newValue and so on. This way the dictionary will always be "up to date" and you don't need to store references to anything.
we are going to take an example of fruits as given in your 2nd edit:
def set_round_val(fruit_dict,round_dict):
fruit_set = set(fruit_dict)
round_set = set(round_dict)
common_set = fruit_set.intersection(round_set) # get common key
for key in common_set:
round_dict[key] = fruit_dict[key] # set modified value in round_dict
return round_dict
fruit_dict = {'apple':34,'orange':30,'mango':20}
round_dict = {'bamboo':10,'apple':34,'orange':20} # values can even be same as fruit_dict
for r in range(1,10):
fruit_set['apple'] = r
round_dict = set_round_val(fruit_dict,round_dict)
print round_dict
Hope this helps.
From what I've gathered from the responses from #BrenBarn and #ebarr, this is the best way to go about the problem (and directly answer EDIT2).
Create a class which encapsulates the common variable:
class Count:
__init__(self,value):
self.value = value
Create the instance of that class:
import Count
no_of_apples = Count.Count(1)
no_of_tennis_balls = Count.Count(5)
no_of_bananas = Count.Count(7)
Create dictionaries with the common variable in both of them:
round = {'tennis_ball':no_of_tennis_balls,'apple':no_of_apples}
fruit = {'banana':no_of_bananas,'apple':no_of_apples}
print(round['apple'].value) #prints 1
fruit['apple'].value = 2
print(round['apple'].value) #prints 2
I have a group of variables named k1, k2 k3....k52. They variables are lists/numpy arrays depending on the scenario. Essentially I'd like to perform the same manipulation on them en masse within a loop, but am having trouble ierating over them. Essentially what i'd like is something like this:
for i in arange(0,52):
'k'+ str(i) = log10(eval('k' + str(i)))
Obviously i know the above wont work, but it gives the idea. My actual attempt is this:
for i in arange(0,10):
rate = eval('k' + str(i))
rate = np.array(rate,dtype=float)
rate = log10(rate)
rate.tolist()
vars()[rate] = 'k' + str(i)
(Its changed to a numpy array so i can log it, and then back to a list so i change the variable name back to what it was) Thanks for any help you can provide. I get the feeling this is something quite simple, but its escaping me at the moment.
edit: thanks very much for the answers, i should have explained that I can't really store them a set array, they need to remain as independent variables for reasons i don't really want to go into.
The line:
vars()[rate] = 'k' + str(i)
has to be replaced by:
vars()['k' + str(i)]=rate
If the items are all globals you can use the globals() call to get a mapping, then manipulate them:
g = globals()
for i in arange(0,52):
varname = 'k{}'.format(i)
g[varname] = log10(g[varname])
but you really want to just store all those items in a list or dictionary instead.
I am coding a function that solves an arbitrary number of simultaneous equations. The number of equations is set by one of the parameters of the function and each equation is built from a number of symbols - as many symbols as there are equations. This means that I can't simply hardcode the equations, or even the symbols needed to put together the equations; the function needs to be able to handle any number of equations. So, my question is, how do I produce a list of symbols?
I have one possible solution, but my gut tells me that it's not going to be very efficient. Please let me know if there is a better way of doing this.
I'm new to SymPy and am still feeling my way about. As far as I can see, Symbols need to be defined with a string. Therefore, I can produce a series strings via appending an incrementing number to a letter (say 't0', 't1', etc), add them to a list and then create the symbols using those strings as parameters. Those symbols would themselves be stored in a list and would be used to produce the equations.
def solveEquations(numEquations):
symbolNameList = []
symbolList = []
equationList = []
for i in range(numEquations):
name = 't' + str(i)
symbolNameList.append(name)
symbolList.append(Symbol(name))
for i in range(numEquations):
equation = 0
for sym in symbolList:
equation += sym ** i # Or whatever structure the equation needs
equationList.append(equation)
#Then go on to solve the equations...
Is this the best way of doing this, or is there a more efficient approach?
The symbols function can be used to easily generate lists of symbols
In [1]: symbols('a0:3')
Out[1]: (a₀, a₁, a₂)
In [2]: numEquations = 15
In [3]: symbols('a0:%d'%numEquations)
Out[3]: (a₀, a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈, a₉, a₁₀, a₁₁, a₁₂, a₁₃, a₁₄)
numbered_symbols("t") will return a generator that generates t0, t1, t2, etc. You can use the start parameter to choose a different starting value. And if you want to use dummy variables, use numbered_symbols("t", cls=Dummy).
Don't know if add any more useful information to the topic, but I use the following method to create a list of symbolic variables:
x = [sympy.symbols('x%d' % i) for i in range(3)]
And then I can use it normally in an equation:
eq = x[0]**2 + x[1]*2 + x[2]
print(sympy.diff(eq,x[0]))
>>> 2*x0
With locals() and dictionary comprehension, you could iteratively generate both symbols and python local variables with a similar name. For example:
>>> symbols_dict = dict(('a%d'%k, symbols('a%d'%k)) for k in range(3))
>>> locals().update(symbols_dict)
Checking that it works:
>>> print(expand((a0+a2)*(a0+a1**2)))
a0**2 + a0*a1**2 + a0*a2 + a1**2*a2
You could make a subclass of dict which automatically returns Symbols:
import sympy as sym
class SymDict(dict):
# http://stackoverflow.com/a/3405143/190597
def __missing__(self, key):
self[key]=sym.Symbol(key)
return self[key]
def solveEquations(numEquations):
symbol = SymDict()
symbolList = ['t'+str(i) for i in range(numEquations)]
equationList = [sum(symbol[s]**i for s in symbolList)
for i in range(numEquations)]
print(equationList)
solveEquations(3)
# [3, t0 + t1 + t2, t0**2 + t1**2 + t2**2]
I like the approach given by #j-p-sena and what I am going to suggest looks a lot like it. The difference is that you don't have to know how many symbols you are going to need -- you will just have access to as many as you need by index. Use the IndexedBase as your symbol:
>>> x = IndexedBase('x') # you've got access to a virtual array of x values
>>> solve(x[1]**2 + 1/x[4], x[4])
[-1/x[1]**2]
For display purposes you might want to create a replacement dictionary. To create numbered symbols you could do
>>> reps = dict(zip([x[i] for i in range(n_used+1)], numbered_symbols('c')))
>>> (x[2]**2 + 1/x[4]).subs(reps)
c2**2 + 1/c4
Or, if you are using less than 26 symbols you could use letters with
>>> reps = dict(zip([x[i] for i in range(n_used+1)], symbols('a:z')))
>>> (x[2]**2 + 1/x[4]).subs(reps)
c**2 + 1/e
BTW, x is an IndexedBase and x[1] is an Indexed object whose .base is x and whose .indices are a tuple of whatever numbers appear in the brackets. Both the IndexedBase and Indexed will show up in a .free_symbols query.
>>> (x[1,2] + 3).free_symbols
{x, x[1, 2]}
>>> x[1, 2].indices
(1, 2)
>>> x[1].base
x
Your approach is fine, though there's no need to store the symbol names separately (you can access a symbol's name via its name property).
Also, you could express the symbol creation a little more concisely (though no more efficiently), e.g.:
symbolList = map(lambda i: Symbol('t' + str(i)), xrange(numEquations))
However, for your use case (temporary variables), dummy variables are probably the way to go:
symbolList = map(Dummy, xrange(numEquations))
This isn't really any more efficient, since internally the Dummy class is also using a counter to generate unique names, but it's a bit cleaner and clearer.
Very beginner question but it is driving me mad. sample1, sample2 etc. are Pygame.mixer.sound objects.
sample_list = []
sample_list.append(sample1)
sample_list.append(sample2)
sample_list.append(sample3)
Is fine, but I want to do that using a for style loop, e.g.
for j in range(1, 3, 1):
sample_list.append(sample + j)
But that is trying to add a number to a sound object so isn't right. I can add the equivalent string by;
for j in range(1, 3, 1):
sample_list.append("sample" + str(j))
But that doesn't refer to the objects I want, just adds those strings.
I've tried must permutations of syntax I can think of but it is still alluding me!
Thanks.
Don't store the objects in variables in the first place; store them directly into a list, and then you will be able to index them by integer.
If the integer identifiers are sparse, use a dict indexed by integer.
I would recommend storing these in a dict to begin with. It is almost the same effect for you to reference by a name, but without the explicit object symbol for each:
samples = {
"sample1": Sample(),
"sample2": Sample()
}
samples['sample3'] = Sample()
This is the preferred approach when you have a dynamic number of objects you are creating and want to be able to grab them by a name later. You can store 100's of these in your dict without cluttering up your namespace.
And later if you are trying to apply this to your loop, you can reference the string names:
for i in xrange(1,4):
sample_list.append(samples["sample" + str(i)])
As a side note another way to get attributes by name when they live on some object is to use getattr. Assume you have this:
class Sampler(object):
pass
sampler = Sampler()
sampler.sample1 = Sample()
sampler.sample2 = Sample()
sampler.sample3 = Sample()
You can then reference by name via: getattr(sampler, "sample1")
Note: As mentioned in comments by #Marcin, if you don't care about having a string identifier to be able to look up your items, and they are just purely sequential by number, you can use this same approach but with a list. It depends on your needs.
It is possible you might want to end up doing something like:
samples = {
"bang1": Sample(),
"bang2": Sample(),
"bang3": Sample(),
"shot1": Sample(),
"shot2": Sample(),
...
}
... Which would then allow you to look up sequential subsets of those sounds.
You can dynamically load variables from the locals() mapping:
for j in range(1, 4):
sample_list.append(locals()["sample" + str(j)])
Generally, you want to avoid such tricks; find other ways to store your sample variables, in a mapping or a list for example.
Looks like the wrong approach, but nevertheless.
sample_list = [eval('sample' + str(i)) for i in range(1, 4)]