阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1.循环
(1)for
for letter in 'laioffer':
print(letter)l
a
i
o
f
f
e
r
(2)range(x): 左闭右开
for i in range(1, 5, 2):
print(i)1
3
for i in range(10, 10):
print('num:', i)(3)break, continue: 只针对上一个while/for loop
2.Function
Global variables vs. Local variables
total = 0
def sum0(arg1, arg2):
total = arg1 + arg2
print('Inside the function local total:', total)
sum0(10, 20)
print('Outside the function local total:', total)Inside the function local total: 30
Outside the function local total: 0
total = 0
def sum0(arg1, arg2):
global total
total = arg1 + arg2
print('Inside the function local total:', total)
sum0(10, 20)
print('Outside the function local total:', total)Inside the function local total: 30
Outside the function local total: 30
3.Pass-by-object-reference
(1)reassign vs. modify
Reference: Stack
Object: Heap
名称重新绑定示意: x=[0]; y=x 时两个名称指向同一列表;执行 y=[1] 后,x→[0],y→[1]。原对象没有被修改。
整理注: Python 传参可理解为对象共享;栈/堆图仅是名称绑定的概念示意,不承诺所有解释器的内存布局。
def reassign():
x = [0]
y = x
y = [1] # reassign a new object
print(x)
reassign()[0]
原地修改示意: x=[0]; y=x; y[0]=1 后仍只有同一个列表,x→[1]←y。
def modify():
x = [0]
y = x
y[0] = 1 # dereference and modify old object
print(x)
modify()[1]
(2) Example 1
例1名称关系: x=[0]; y=x; x=[1] 后,y仍绑定旧列表[0],x绑定新列表[1]。下一段先改共享对象,再只给局部名称y重新赋值,所以x保留[1]。
def foo():
x = [0]
y = x
x = [1]
print(y)
foo()[0]
def foo():
x = [0]
y = x
y[0] = 1
y = [2]
y[0] = 3
print(x)
foo()[1]
(3) Example 2
函数调用关系: 调用reassign(x)时,局部参数lst与外部x先共享[0];lst=[1]只改变局部绑定,函数外仍为[0]。
def reassign(lst): # 局部名称重新绑定,不发生复制
lst = [1] # create a new object
def foo():
x = [0]
reassign(x)
print(x)
foo()[0]
函数内修改关系: modify(x)中的lst[0]=1修改共享列表,所以外部x也变成[1]。
def modify(lst):
lst[0] = 1
def foo():
x = [0]
modify(x)
print(x)
foo()[1]
分步跟踪: x[0]=1修改调用方列表;随后局部x=[2]切换到新对象,再把新对象改为[3]。调用方仍指向第一步的[1]。
def bar(x):
x[0] = 1
x = [2]
x[0] = 3
def foo():
x = [0]
bar(x)
print(x)
foo()[1]
(4) Example 3
def foo(x):
x.append(1)
x = [2]
x.append(1)
return x
x = [0]
foo(x)
print(x)[0, 1]
def foo(x):
x.append(1)
x.append(1)
x = [2]
return x
x = [0]
foo(x)
print(x)[0, 1, 1]
def foo(x):
x = [2]
x.append(1)
x.append(1)
return x
x = [0]
foo(x)
print(x)[0]
(5) shallow copy
浅拷贝示意: y=x.copy()创建一个新外层列表。例中元素是整数,修改x[0]不改变y[0];如果元素是嵌套列表,内层对象仍可能共享。
x = [0]
y = x.copy()
x[0] = 1
print(y)[0]