【问题标题】:Cannot return the values in the list无法返回列表中的值
【发布时间】:2018-09-15 16:35:21
【问题描述】:

我想返回列表的最终值 new_list[3] 但它最后什么也不返回。我可以使用 print 函数获得 new_list[3] 的最终值。我对返回函数感到很困惑。 2 for 循环结束时是否有可能返回 new_list[times] ?

original_list = [100,300,400,900,1500]

def filter_list(_list,times):

    L = len(_list)
    new_list = [list(_list) for k in range(times+1)]
    for k in range (0,times):
        for j in range (0,L):
            if j == 0: #exclude the term [j-1] because new_list[-1] is not exist
                new_list[k+1][j] = int(new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
            elif j == L-1: #exclude the term [j+1] because new_list[L] is not exist
                new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2)
            else:
                new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
    return (new_list[times])

filter_list(original_list,3)

【问题讨论】:

  • 我收到[263, 561, 744, 763, 436]
  • print(filter_list(original_list,3)) 看到结果了吗?
  • @Austin 我用的是jupyter notebook,自动打印最后一行!
  • @KhalilAlHooti OP 可能没有使用 Jupyter 笔记本。 ;)
  • @Austin 我认为他的功能本身有问题,而不是缺少打印输出。!!

标签: python python-3.6


【解决方案1】:

函数能够将值“返回”回调用它的作用域。如果这个变量没有被存储或传递给另一个函数,它就会丢失。

例如:

定义 f(x): 返回 x + 1 f(5)

不会打印任何内容,因为从 f(5) 调用返回的 6 没有执行任何操作。

要输出函数返回的值,我们可以将其传递给print() 函数:

print(f(5))

或者在你的情况下:

print(filter_list(original_list, 3))

【讨论】:

  • 有没有其他方法可以不使用打印而只返回?因为这是我的任务的一部分,它只允许我使用返回函数。
  • @Shen 如果你想要一个输出,你必须使用 print simple as that。
【解决方案2】:

这就是返回函数的作用:

return 语句结束函数调用的执行并将结果(即 return 关键字后面的表达式的值)“返回”给调用者。如果 return 语句没有表达式,则返回特殊值 None。

【讨论】:

    【解决方案3】:

    您正在退回该项目,但没有将其分配给任何东西

    x = filter_list(original_list,3)
    
    print(x)
    

    这将做的是将您从函数调用返回的任何内容分配给在这种情况下x 的变量,然后您的变量将保存您现在返回的任何内容

    这是一个可视化的简单模型

    def something():
        x = 1
        return x
    
    def something_print():
        x = 1
        return print(x)
    
    a = something()
    print(a)
    
    something_print()
    
    (xenial)vash@localhost:~/python/stack_overflow$ python3.7 fucntion_call.py 
    1
    1
    

    【讨论】:

      猜你喜欢
      • 2011-07-05
      • 1970-01-01
      • 2016-01-15
      • 2017-11-26
      • 2016-01-21
      • 2020-02-19
      • 1970-01-01
      • 2021-12-27
      • 2018-09-28
      相关资源
      最近更新 更多