【问题标题】:Python append value to a list returned from a function via for loopPython将值附加到通过for循环从函数返回的列表中
【发布时间】:2017-01-16 12:30:45
【问题描述】:

我有一个函数:

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

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 

【问题讨论】:

  • 您将每次迭代的列表设置为函数的返回值。我相信你正在尝试.append(val)
  • @TheLazyScripter:你能说得更具体点吗?
  • 请发布整个代码,下面的每个答案都会并且确实有效。唯一的其他解释是其他地方的错误。
  • 是的@TheLazyScripter。我认为问题必须出在函数内,但如果所有这些答案都导致空列表,这似乎很奇怪。即使函数返回None 或空字符串,这些仍将附加到列表中。
  • @TheLazyScripter:请看一下整个函数。它将两个值作为元组返回,即(0.16552264676265405, 0.011976798379824433)

标签: python list function for-loop append


【解决方案1】:

您可以先使用列表推导,通过 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)

【讨论】:

  • list_alist_b 仍然是空的!!
【解决方案2】:

你的意思是这样的:

list_a = []
list_b = []

for i in range(10,100,10):
    a, b = function(i,30)
    list_a.append(a)
    list_b.append(b)

【讨论】:

    【解决方案3】:

    你可能需要试试map()函数,更友好~~

    Understanding the map function

    这应该与python 3中的相同: def 映射(函数,可迭代): 对于 i 在可迭代中: 产生函数(i)

    在python 2 map下会返回完整列表

    【讨论】:

      【解决方案4】:

      这样的事情应该可以工作:

      # 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)
      

      【讨论】:

      • 您能否为您的答案添加一些解释?仅显示代码可能会让某些人感到困惑。
      • 感谢@AndréKool,我在代码中添加了一些 cmets :)
      猜你喜欢
      • 2020-04-25
      • 1970-01-01
      • 2012-10-30
      • 2020-02-27
      • 1970-01-01
      • 2021-12-17
      • 2021-05-19
      • 2015-04-27
      • 2015-08-08
      相关资源
      最近更新 更多