目前我对编程有点失意,并希望就此事寻求建议。我的问题是,是否可以在循环中将变化的变量(例如2,3,4)分配给递增的变量名称(例如file1,file2 ......等)?
如果是这样,我该怎么做呢?
我有一段脚本,我一直试图实现上述功能:
var=0
IDnumber=1
for i in range (5):
Sample_mean=df.iloc[[var,var+1]].mean(axis=0) #calculating mean from two rows in pandas dataframe. Sample_mean is the numerical variable.
print ("mean of the samples at timepoint 1=")
print (Sample_mean)
var_for_row=var_for_row+2
Sample_mean=df.iloc[[var_for_row,var_for_row+1]].mean(axis=0)
print ("mean of the samples at timepoint 2=")
print (Sample_mean)
label='file_%d'%(IDnumber,) #I am incrementing the variable label here
label=str(label)
global label #This is to avoid the NameError: global name 'pt_1' is not defined error. However, I still get the error.
label=Sample_mean
var_for_row+=2
print 'var_for_row=%s'%var_for_row
IDnumber+=1
print file_1 #Error occurs at this line
我尝试了上面的代码,但收到错误NameError: global name 'file_1' is not defined
。
答案 0 :(得分:0)
你不能增加一个"名称"变量。使用document.addEventListener('DOMContentLoaded', functionName);
存储多个值。
你可以增加"文本"如果你知道模式,变量就会成立。
list
输出:
pat = 'file_{}'
myFiles = []
for n in range(4):
myFiles.append(pat.format(n))
print ( myFiles[-1])
print(myFiles)
这里:
file_0
file_1
file_2
file_3
['file_0', 'file_1', 'file_2', 'file_3']
与
相同label='file_%d'%(5,) #I am incrementing the variable label here
# label=str(label) # not needed at all - it is already a string
见:
用于高级格式化选项。