Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration over variable names in python?

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.

like image 435
Nathan Bush Avatar asked Mar 01 '13 15:03

Nathan Bush


1 Answers

The line:

vars()[rate] = 'k' + str(i)

has to be replaced by:

vars()['k' + str(i)]=rate
like image 85
sissi_luaty Avatar answered Oct 05 '22 22:10

sissi_luaty