Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python函数和操作_Python_Function - Fatal编程技术网

Python函数和操作

Python函数和操作,python,function,Python,Function,为什么n在执行第二个函数后发生变化? 我不知道为什么会这样。我甚至都没有用过环球? a=a*2和a*=2之间有什么区别吗? 请帮帮我 def f(a): print(f"Before: {a}") a = a * 2 print(f"After: {a}") def d(a): print(f"Before: {a}") a *= 2 print(f"After: {a}") n = [

为什么n在执行第二个函数后发生变化? 我不知道为什么会这样。我甚至都没有用过环球? a=a*2和a*=2之间有什么区别吗? 请帮帮我

def f(a):
  print(f"Before: {a}")
  a = a * 2
  print(f"After: {a}")

def d(a):
  print(f"Before: {a}")
  a *= 2
  print(f"After: {a}")


n = [1,2,3,4]

print("First fun")
f(n)
print(f"  n: {n}")

print("Second fun")
d(n)
print(f"  n: {n}")
输出:

First fun
Before: [1, 2, 3, 4]
After: [1, 2, 3, 4, 1, 2, 3, 4]
  n: [1, 2, 3, 4]
Second fun
Before: [1, 2, 3, 4]
After: [1, 2, 3, 4, 1, 2, 3, 4]
  n: [1, 2, 3, 4, 1, 2, 3, 4]

最初,
a
n
是对同一列表的引用<代码>a*2创建一个新列表;当您将其分配给
a
时,
a
不再引用与
n
相同的列表<另一方面,code>a*=2修改了
a
引用的列表,因此从
n
也可以看到更改。

因为增广赋值运算符将按常规在适当的位置工作
a=a*2
不起作用,它会创建一个新列表。