python: 列表、字典

来源:互联网 发布:省委宣传部 知乎 编辑:程序博客网 时间:2024/05/16 16:55

列表的赋值语句创建拷贝。你得使用切片操作符来建立序列的拷贝。

# Filename: reference.pyprint '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', shoplistprint 'mylist is', mylist# notice that both shoplist and mylist both print the same list without# the 'apple' confirming that they point to the same objectprint 'Copy by making a full slice'mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint 'shoplist is', shoplistprint 'mylist is', mylist# notice that now the two lists are different
输出:$ python reference.pySimple Assignmentshoplist is ['mango', 'carrot', 'banana']mylist is ['mango', 'carrot', 'banana']Copy by making a full sliceshoplist 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这个符号。

                                             
0 0
原创粉丝点击