列表的赋值语句不创建拷贝。你得使用切片操作符来建立序列的拷贝。
# Filename: reference.py
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different
输出:
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
1. 首先给出一个字典对象a:
>>> a = {'a':'a_v','b':'b_v'}
2. 下面对字典进行遍历:
方式1:(错误方式)
>>> for key in a:
print %(key, a[key])
SyntaxError: invalid syntax
>>> for key in a:print 'key: %s, value: %s' %(key, a[key])key: a, value: a_vkey: b, value: b_v方式2:(正确方式)
3. 解析:
注意:方式1错误是因为缺少了%s这个符号。