【发布时间】:2017-01-16 12:30:45
【问题描述】:
我有一个函数:
def function(x,y):
do something
print a,b
return a,b
现在我使用 for 循环,例如:
for i in range(10,100,10):
function(i,30)
它通过 for 循环打印给定输入值的值 a,b。
如果我说例如function(10,30),它也会返回a,b:
Out[50]: (0.25725063633960099, 0.0039189363571677958)
我想将通过 for 循环为我的不同输入参数 (x,y) 获得的 a,b 的值附加到两个空列表中。
我试过了
for i in range(10,100,10):
list_a,list_b = function(i,30)
但是list_a 和list_b 仍然是空的。
编辑:
我也试过了:
list_a = []
list_b = []
for i in range(10,100,10):
list_a.append(function(i,30)[0])
list_b.append(function(i,30)[1])
但是list_a 和list_b 是空的!
我不明白的是,当我打电话时
function(10,30)[0]
例如,它输出一个值!但为什么我无法将其附加到列表中?
这是少数人提出的完整功能。
def function(N,bins):
sample = np.log10(m200_1[n200_1>N]) # can be any 1D array
mean,scatter = stats.norm.fit(sample) #Gives the paramters of the fit to the histogram
err_std = scatter/np.sqrt(len(sample))
if N<30:
x_fit = np.linspace(sample.min(),sample.max(),100)
pdf_fitted = stats.norm.pdf(x_fit,loc=mean,scale=scatter) #Gives the PDF, given the parameters from norm.fit
print "scatter for N>%s is %s" %(N,scatter)
print "error on scatter for N>%s is %s" %(N,err_std)
print "mean for N>%s is %s" %(N,mean)
else:
x_fit = np.linspace(sample.min(),sample.max(),100)
pdf_fitted = stats.norm.pdf(x_fit,loc=mean,scale=scatter) #Gives the PDF, given the parameters from norm.fit
print "scatter for N>%s is %s" %(N,scatter)
print "error on scatter for N>%s is %s" %(N,err_std)
print "mean for N>%s is %s" %(N,mean)
return scatter,err_std
【问题讨论】:
-
您将每次迭代的列表设置为函数的返回值。我相信你正在尝试
.append(val)。 -
@TheLazyScripter:你能说得更具体点吗?
-
请发布整个代码,下面的每个答案都会并且确实有效。唯一的其他解释是其他地方的错误。
-
是的@TheLazyScripter。我认为问题必须出在函数内,但如果所有这些答案都导致空列表,这似乎很奇怪。即使函数返回
None或空字符串,这些仍将附加到列表中。 -
@TheLazyScripter:请看一下整个函数。它将两个值作为元组返回,即
(0.16552264676265405, 0.011976798379824433)
标签: python list function for-loop append