我有一个功能:
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
。
如果我说例如a,b
,它也会返回function(10,30)
:
Out[50]: (0.25725063633960099, 0.0039189363571677958)
我想通过for循环将我的不同输入参数a,b
获得的(x,y)
的值附加到两个空列表中。
我试过
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
答案 0 :(得分:4)
你可以先使用list comprehension,通过zip获取list_a,list_b。
def function(x,y):
return x,y
result = [function(i,30) for i in range(10,100,10)]
list_a, list_b = zip(*result)
答案 1 :(得分:0)
你的意思是这样的:
list_a = []
list_b = []
for i in range(10,100,10):
a, b = function(i,30)
list_a.append(a)
list_b.append(b)
答案 2 :(得分:0)
这样的事情应该有效:
# Define a simple test function
def function_test(x,y):
return x,y
# Initialize two empty lists
list_a = []
list_b = []
# Loop over a range
for i in range(10,100,10):
a = function_test(i,30) # The output of the function is a tuple, which we put in "a"
# Append the output of the function to the lists
# We access each element of the output tuple "a" via indices
list_a.append(a[0])
list_b.append(a[1])
# Print the final lists
print(list_a)
print(list_b)
答案 3 :(得分:-2)
你可能需要尝试map()函数,这更友好~~
Understanding the map function
应该与python 3中的相同: def map(func,iterable): for i in iterable: yield func(i)
在python 2 map下将返回完整列表