Python学习笔记(rev.0)

睁着眼做梦 posted @ 2015年11月20日 15:57 in 蟒蛇 , 2237 阅读

String Manipulation:

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

Like strings (and all other built-in sequence type例如 "str"), lists can be indexed and sliced

List Manipulation:

stupidly wrong: 
>>> cubes = [1, 2, 3, 4, 5]
>>> cubes[:][0] = 0
>>> cubes
[1, 2, 3, 4, 5]
 
correct:
>>> cubes[:1] = [0]
>>> cubes
[0, 2, 3, 4, 5]
 
 

Shallow& Deep Copying:

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Demonstration:

 

import copy

a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]

#Using normal assignment operatings to copy:

d = c

print id(c) == id(d)          # True - d is the same object as c
print id(c[0]) == id(d[0])    # True - d[0] is the same object as c[0]

#Using a shallow copy:

d = copy.copy(c)

print id(c) == id(d)          # False - d is now a new object
print id(c[0]) == id(d[0])    # True - d[0] is the same object as c[0]

#Using a deep copy:

d = copy.deepcopy(c)

print id(c) == id(d)          # False - d is now a new object
print id(c[0]) == id(d[0])    # False - d[0] is now a new object
  • 无匹配

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter