码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记——Coursera

时间:2014-10-16 21:03:23      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   strong   sp   div   

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指向不同的内存。

bubuko.com,布布扣

 

global  vs  local

mutate_part(x)这个函数对a[1]进行了更改,这里a被默认为global;

assign_whole(x)中a则是local。

assign_whole_global(x)中想对全局变量进行更改,所以加上global关键字

bubuko.com,布布扣

 

 

lists  & tuples(多元组)

difference: lists are mutable; tuples are immutable, strings are the same as tuples, immutable.

bubuko.com,布布扣

 

Python学习笔记——Coursera

标签:style   blog   http   color   io   ar   strong   sp   div   

原文地址:http://www.cnblogs.com/beatrice7/p/4029450.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!