繁体   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