列表的赋值语句不创建拷贝。你得使用切片操作符来建立序列的拷贝。
# 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方式2:(正确方式)>>> for key in a:print 'key: %s, value: %s' %(key, a[key])key: a, value: a_vkey: b, value: b_v
3. 解析:
注意:方式1错误是因为缺少了%s这个符号。
本文探讨了Python中列表赋值与拷贝的区别,通过实例演示了如何正确地复制列表避免引用问题,并展示了两种不同的字典遍历方法。
1384

被折叠的 条评论
为什么被折叠?



