今天学习了第九章的数据结构的字典、序列、引用,并且编写了一个简单备份的python脚本。

1.字典:键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。

#!/usr/bin/python
ab={'reed':'reed@reed.com','deer':'deer@deer.com'}
print 'reed address is %s'%ab['reed']
# add a key
ab['lemon']='lemon@lemon.com'
#del a key
del ab['deer']
print '\nthere are %d contacts in the address-book\n'%len(ab)
for name,address in ab.items():
        print 'contact %s at %s'%(name,address)
if 'reed' in ab:
        print '\nreed addrss is %s'%ab['reed']
[root@reed 0503]# ./using_dict.py
reed address is reed@reed.com
there are 2 contacts in the address-book
contact lemon at lemon@lemon.com
contact reed at reed@reed.com
reed addrss is reed@reed.com

2.序列:列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。

[root@reed 0503]# cat seq.py
#!/usr/bin/python
shoplist=['apple','manago','carrot','banana']
print 'item 0 is',shoplist[0]
print 'item 1 is',shoplist[1]
print 'item 2 is',shoplist[2]
print 'item 3 is',shoplist[3]
print 'item -1 is',shoplist[-1]
print 'item -2 is',shoplist[-2]
print '\n'
print 'item 1 to 3 is',shoplist[1:3]
print 'item 2 to end is',shoplist[2:]
print 'item 1 to -1 is',shoplist[1:-1]
print 'item start to end is',shoplist[:]
print '\n'
name='swaroop'
print 'characters 1 to 3 is',name[1:3]
print 'characters 2 to end is',name[2:]
print 'characters 1 to -1 is',name[1:-1]
print 'characters start to end is',name[:]
[root@reed 0503]# ./seq.py
item 0 is apple
item 1 is manago
item 2 is carrot
item 3 is banana
item -1 is banana
item -2 is carrot
item 1 to 3 is ['manago', 'carrot']
item 2 to end is ['carrot', 'banana']
item 1 to -1 is ['manago', 'carrot']
item start to end is ['apple', 'manago', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop

切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

3.引用

[root@reed 0503]# cat reference.py
#!/usr/bin/python
print 'simple assignment'
shoplist=['apple','manago','carrot','banana']
mylist=shoplist
del shoplist[0]
print 'shoplist is',shoplist
print 'mylist is',mylist
print 'copy by making a full slice'
mylist=shoplist[:]
del mylist[0]
print 'shoplist is',shoplist
print 'mylist is',mylist
[root@reed 0503]# ./reference.py
simple assignment
shoplist is ['manago', 'carrot', 'banana']
mylist is ['manago', 'carrot', 'banana']
copy by making a full slice
shoplist is ['manago', 'carrot', 'banana']
mylist is ['carrot', 'banana']