功能不实时更新列表python

Function don't update the list realtime python

def func(a,b):
a=a.append(b)
if a is not None:
    for i in a:
        print(i)
li=[1,2,3]
def testcall():
    c=10
    func(li,c)
if __name__=='__main__':
        test()

为什么不打印更新列表 即使我在测试函数中更新列表然后发送它,它也不会打印任何内容。有没有人知道为什么函数有这种奇怪的行为。 如果我让“func”只接受一个参数并在“test”中发送更新列表,它仍然不会显示任何内容。

为了回答您主要关心的“为什么它不打印任何东西”,当您执行 a = a.append(b) 时,内部 a.append(b) returns 什么也没有,所以 a没什么。此外,您的代码存在一个主要问题,因为它缺少正确的缩进,并且您将对 testcall() 的调用错误命名为 test()。这可能就是你想要的。

def func(a,b):
  print(a) # [1,2,3]
  a.append(b) 
  print(a) # [1,2,3,10]
  if a is not None:
    for i in a:
      print(i)

li=[1,2,3]

def testcall():
  c=10
  func(li,c)

if __name__=='__main__':
  testcall()

您可以在 IDLE 中进行一些实验:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = a.append(b)
>>> c
>>> a
[1, 2, 3, [4, 5, 6]]
>>>