Reputation: 9363
I have a function:
def function(x,y):
do something
print a,b
return a,b
Now I use a for loop like:
for i in range(10,100,10):
function(i,30)
which prints the values a,b
for the given input values via the for loop.
It also returns a,b
if I say for example function(10,30)
like:
Out[50]: (0.25725063633960099, 0.0039189363571677958)
I would like to append the values of a,b
obtained for my different input parameters (x,y)
via the for loop to two empty lists.
I tried
for i in range(10,100,10):
list_a,list_b = function(i,30)
but list_a
and list_b
are still empty.
EDIT:
I have also tried:
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])
But list_a
and list_b
are empty!
What I don't understand is that, when I call
function(10,30)[0]
for instance, it outputs a value! But why am I not able to append it to a list?
Here is the entire function as asked by a few.
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
Upvotes: 0
Views: 8178
Reputation: 46
Something like this should work:
# 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)
Upvotes: 1
Reputation: 2691
you can use list comprehension first, get list_a, list_b via zip.
def function(x,y):
return x,y
result = [function(i,30) for i in range(10,100,10)]
list_a, list_b = zip(*result)
Upvotes: 5
Reputation: 43
you may need to try map() function, which is more friendly~~
Understanding the map function
which should be the same as in python 3: def map(func, iterable): for i in iterable: yield func(i)
under python 2 map will return the full list
Upvotes: -2
Reputation: 4893
You mean something like that:
list_a = []
list_b = []
for i in range(10,100,10):
a, b = function(i,30)
list_a.append(a)
list_b.append(b)
Upvotes: 0