Python学习笔记——Coursera
Someting about Lists mutation
1 ################################### 2 # Mutation vs. assignment 3 4 5 ################ 6 # Look alike, but different 7 8 a = [4, 5, 6] 9 b = [4, 5, 6] 10 print "Original a and b:", a, b 11 print "Are they same thing?", a is b 12 13 a[1] = 20 14 print "New a and b:", a, b 15 print 16 17 ################ 18 # Aliased 19 20 c = [4, 5, 6] 21 d = c 22 print "Original c and d:", c, d 23 print "Are they same thing?", c is d 24 25 c[1] = 20 26 print "New c and d:", c, d 27 print 28 29 ################ 30 # Copied 31 32 e = [4, 5, 6] 33 f = list(e) 34 print "Original e and f:", e, f 35 print "Are they same thing?", e is f 36 37 e[1] = 20 38 print "New e and f:", e, f 39 print 40 41 42 ################################### 43 # Interaction with globals 44 45 46 a = [4, 5, 6] 47 48 def mutate_part(x): #注:这里的a默认为global 49 a[1] = x 50 51 def assign_whole(x): 52 a = x 53 54 def assign_whole_global(x): 55 global a 56 a = x 57 58 mutate_part(100) 59 print a 60 61 assign_whole(200) 62 print a 63 64 assign_whole_global(300) 65 print a
这里的赋值需要注意:
b = a ,则a, b指向同一块内存,对a[1]或者b[1]赋值, 都可以改变这个list;
b = list(a), 则a, b指向不同的内存。
global vs local
mutate_part(x)这个函数对a[1]进行了更改,这里a被默认为global;
assign_whole(x)中a则是local。
assign_whole_global(x)中想对全局变量进行更改,所以加上global关键字
lists & tuples(多元组)
difference: lists are mutable; tuples are immutable, strings are the same as tuples, immutable.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。