![](/img/trans.png)
[英]making a list from values returned by a function inside a for-loop in python
[英]Python append value to a list returned from a function via for loop
我有一個功能:
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
它也會返回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
您可以先使用列表理解功能,並通過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)
這樣的事情應該起作用:
# 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)
您的意思是這樣的:
list_a = []
list_b = []
for i in range(10,100,10):
a, b = function(i,30)
list_a.append(a)
list_b.append(b)
您可能需要嘗試map()函數,它更友好~~
這應該與python 3中的相同:def map(func,iterable):對於i中的iterable:yield func(i)
python 2下的map將返回完整列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.