簡體   English   中英

Python將值附加到通過for循環從函數返回的列表中

[英]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_alist_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_alist_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM