列表
基本操作
>>>len([1,3,4])
3
>>>[1,2,3]+[4,5,6] +号两边必须是相同类型
[1,2,3,4,5,6]
>>>['ni!']*4
['ni!','ni!','ni!','ni!']
>>>str([1,2])+"34"
'[1,2]34'
>>>[1,2]+list("34")
[1,2,3,4]
列表迭代和解析
>>>3 in [1,2,3]
true
>>>for x in [1,2,3]:
print (x,end=' ');
1,2,3
>>> res = [c *4 for c in 'spam'];
>>>res
['ssss','pppp','aaaa','mmmm']
索引 分片和矩阵
>>>l = ['aa','bb','cc']
>>>l[2]
'cc'
>>>l[-2]
'bb'
>>>l[1:]
['bb','cc']
列表是可变的,他们支持原处改变列表对象的操作
索引与分片的赋值
>>>l = ['aa','bb','cc']
>>>l[1]='dd'
>>>l
['aa','dd','cc']
>>>l[0:2]=['xx','yy']
>>>l
['xx','yy','cc']
列表方法的调用
>>>l.append('aa')
>>>l
['xx','yy','cc','aa']
>>>l.sort()
>>>l
['aa','cc','xx','yy']
>>>l.sort(key=str.lower) 按字符串的小写排序
['aa','cc','xx','yy']
>>>l.sort(key=str.lower,reverse = true) 翻转
>>>l
['yy','xx','cc','aa']
>>>l = [1,2]
>>>l.extend([3,4,5]) 扩展
>>>l
[1,2,3,4,5]
>>>l.pop() 推出最后一个元素
>>>l
[1,2,3,4]
>>>l.reverse() 翻转
>>>l
[4,3,2,1]
>>>l = []
>>>l.append(1) 添加数据
>>>l.append(2)
>>>l
[1,2]
>>>l = ['aa','bb','cc']
>>>l.index('aa') 索引
0
>>>l.insert(1,'xx') 插入
>>>l
['aa','xx','bb','cc']
>>>l.remove('xx') 移除
>>>l
['aa','bb','cc']
>>>l.pop(1) 移除索引元素
>>>l
['aa','cc']
其他常见的列表操作
>>>l = ['aa','bb','cc']
>>>del l[0] 删除列表元素
>>>l
['bb','cc']
>>>del l[1:] 删除列表分片
>>>l
['aa']
>>>l = ['aa','bb','cc']
>>>l[1:] = [] 删除列表分片
>>>l
['aa']
字典
除了列表外,字典也许就是python中最灵活的数据结构了
字典的基本操作
>>>d = {'spam':2,'ham':1,'eggs':3}
>>>d['spam'] 通过key取值
2
>>>d
{'spam':2,'ham':1,'eggs':3}
>>>len(d) 长度
3
>>>'ham'in d 成员
true
>>>list(d.keys()) 将字典的key转换成list
['eggs','ham','spam']
原处修改字典
>>>d['ham'] = ['grill','bake','fry'] 赋值
>>>d
{'spam':2,'ham':['grill','bake','fry'],'eggs':3}
>>>del d['eggs'] 删除
>>>d
{'spam':2,'ham':['grill','bake','fry']}
其他的字典方法
>>>d = {'spam':2,'ham':1,'eggs':3}
>>>list(d.values())
[3,1,2]
>>>list(d.items())
[('eggs',3),('ham',1),('spam',2)]
>>>d.get('spam')
2
>>>print(d.get('toast'))
None
>>>d.get('toast',88) 默认值
88
字典的update方法类似于合并 相同的覆盖
>>>d2 = {'toast':4,'muffin':5,'eggs':3}
>>>d.update(d2)
>>>d
{'spam':2,'ham':1,'eggs':5,'toast':4,'muffin':5}
>>>d.pop('muffin')
{'spam':2,'ham':1,'eggs':5,'toast':4}