python学习记录(第四天)

索引与分片的赋值
>>> l=[1,2,3]
>>> 
>>> 
>>> l[1]
2
>>> l[2]=5
>>> l
[1, 2, 5]
>>> l[0:2]
[1, 2]
>>> l[0:2]=[4,5]
>>> l
[4, 5, 5]
列表方法调用
>>> l.append(23)
>>> l
[4, 5, 5, 23]
>>> l.extend([3,56,32])
>>> l
[4, 5, 5, 23, 3, 56, 32]
>>> l.sort()
>>> l
[3, 4, 5, 5, 23, 32, 56]
>>> l.reverse()
>>> l
[56, 32, 23, 5, 5, 4, 3]
>>> l.pop(2)
23
>>> l
[56, 32, 5, 5, 4, 3]
>>> l.pop()
3
>>> l
[56, 32, 5, 5, 4]
当pop中没指定偏移量的时候默认就是最后一位。
其他常见列表操作
>>> l=[45,23,12,31,1,55,36]
>>> l
[45, 23, 12, 31, 1, 55, 36]
>>> del l[2]
>>> l
[45, 23, 31, 1, 55, 36]
>>> l[1]=[]
>>> l
[45, [], 31, 1, 55, 36]
>>> l[1:]=[]
>>> l
[45]
原处修改字典
如果不存在的key那么则添加,如果存在的key那么是修改该key的值
>>> d['open']=['chia',1,45]
>>> d
{'open': ['chia', 1, 45], 'ham': 2, 'spam': 1}
删除一个key
>>> del d['ham']
>>> d
{'open': ['chia', 1, 45], 'spam': 1}
显示字典d中有些什么key
>>> d.keys()
['open', 'spam']
显示字典d中的key的值是什么
>>> d.values()
[['chia', 1, 45], 1]
显示字典d中的对元组是什么
>>> d.items()
[('open', ['chia', 1, 45]), ('spam', 1)]
get方法将不存在的值不显示,或者临时给不存在的key赋值
>>> d.get('spam')
1
>>> d.get('hello')
>>> d
{'open': ['chia', 1, 45], 'spam': 1}
>>> d.get('hello',88)
88
>>> d
{'open': ['chia', 1, 45], 'spam': 1}
update方法实质就是合并两个字典
>>> d
{'open': ['chia', 1, 45], 'spam': 1}
>>> c={'open':1,'hello':32}
>>> d.update(c)
>>> d
{'open': 1, 'hello': 32, 'spam': 1}
>>> d={'open': ['chia', 1, 45], 'spam': 1}
>>> c.update(d)
>>> c
{'open': ['chia', 1, 45], 'hello': 32, 'spam': 1}
pop方法主要是用来删除一个key并返回它的值
>>> c.pop('spam')
1
>>> c
{'open': ['chia', 1, 45], 'hello': 32}
一个简单的字典案例
>>> table={'cisco':'CCIE','redhat':'RHCA','juniper':'JUNIE'}
>>> for zhengshu in table.keys():
...      print zhengshu,'\t',table[zhengshu]
... 
cisco   CCIE
juniper         JUNIE
redhat  RHCA
避免miss-key错误的三个方法:
1.if语句实现
存在
>>> miss={'cisco':'CCIE','redhat':'RHCA','juniper':'JUNIE'}
>>> if miss.has_key('cisco'):
...    print miss['cisco']
... else:
...    print 0
... 
CCIE
不存在
>>> if miss.has_key('hello'):
...  print miss['hello']
... else:
...  print 0
... 
0
2.try语句实现
存在
>>> try:
...   print miss['cisco']
... except KerError:
...   print 0
... 
CCIE
不存在
>>> try:
...  print miss['hello']
... except KeyError:
...  print 0
... 
0
3.get方法实现
存在
>>> miss.get('cisco',0)
'CCIE'
不存在
>>> miss.get('hello',0)
0

作者: simonchia   发布时间: 2010-11-08