[英]Iteration over variable names in python?
I have a group of variables named k1, k2 k3....k52. 我有一组名为k1,k2 k3 .... k52的变量。 They variables are lists/numpy arrays depending on the scenario. 它们的变量是列表/ numpy数组,具体取决于场景。 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. (它改为一个numpy数组,所以我可以记录它,然后回到列表,所以我将变量名称更改回原来的位置)感谢您提供的任何帮助。 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. 编辑:非常感谢答案,我应该解释说我不能真正存储它们是一个集合数组,它们需要保留为独立变量,原因我并不想进入。
If the items are all globals you can use the globals()
call to get a mapping, then manipulate them: 如果这些项都是全局变量,你可以使用globals()
调用来获取映射,然后操作它们:
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. 但你真的只想将所有这些项目存储在列表或字典中。
The line: 这条线:
vars()[rate] = 'k' + str(i)
has to be replaced by: 必须被替换为:
vars()['k' + str(i)]=rate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.