列表 | 元组 | 字典 | 集合 | |
---|---|---|---|---|
创建 | l = [1, ‘a’, [1, 3], True] | t = (1, ) | d = {‘key’ : ‘value’} | s = set([1, 2, 4, 2, 1]) |
索引 | l[1] | t[0] | d.get(‘key’) | / |
插入 | l.insert(1, ‘3’) / l.append(‘4’) | / | d[‘k1’] = ‘v1’ | s.add(‘9’) |
修改 | l[0] = 4 | / | d[‘k1’] = v | / |
移除 | l.pop(0) | / | d.pop(‘k1’) | s.remove(‘1’) |
其他 | list((1,2,3)) | tuple([1,2,3]) | ‘key’ in d | s1 & s2 |
>>> l = [] # len(l) = 0, 空列表
>>> friuts = ['apple', 'banana', 'orange'] # len(friuts) = 3
>>> L = ['a', 12, True, ['a', 'b']] # len(L) = 4, 元素类型可以不一致
>>> friuts[0]
'apple'
>>> friuts[-1]
'orange'
>>> friuts[4]
Traceback (most recent call last):
File "" , line 1, in <module>
IndexError: list index out of range
>>> friuts.append('lemon') # l.append(x)
>>> friuts.insert(1,'watermelon') # l.insert(i,x)
>>> friuts
['apple', 'watermelon','banana', 'orange','lemon']
>>> friuts.pop(2) # l.pop(i)
>>> friuts
['apple', 'watermelon', 'orange','lemon']
>>> friuts[0] = 'none' # 'apple'被替换成'none'
>>> friuts
['none', 'watermelon', 'orange','lemon']
l.reverse()
l.count('a')
l.index('b')
l.sort()
>>> t = ()
>>> t1 = (1,)
>>> t2 = ('apple', 'banana', 'orange')
>>> t2[1]
'banana'
>>> t = ('a', 'b', ['c', 'd'])
>>> t[2][0] = 'A'
>>> t[2][1] = 'B'
>>> t
('a', 'b', ['A', 'B'])
初始化的tuple:
修改后的tuple:
tup = (3, 2, 3, 7, 8, 1)
tup.count(3)
tup.index(7)
list(reversed(tup))
sorted(tup)
>>> d0 = {'name':'Amey', 'age':18, 'hobby':'study'}
>>> d1 = dict({'name':'Amey', 'age':18, 'hobby':'study'})
>>> d2 = dict([('name':'Amey'), ('age':18), ('hobby':'study')])
>>> d3 = dict(name='Amey', age=18, hobby='study')
>>> d['sexy'] = 'female'
>>> d['age'] = 16
>>> 'class' in d
Traceback (most recent call last):
File "" , line 1, in <module>
KeyError: 'd'
>>> d.get('age')
>>> 16
>>> d.pop('sexy')
>>> s0 = set([])
>>> s = set([1,1,2,2,3,3])
>>> s
{1,2,3}
>>> s.add('a')
>>> s
{1,2,3,'a'}
>>> s.remove('1')
>>> s
{2,3,'a'}
>>> s1 = ([2,3,4,6,8])
>>> s2 = ([1,3,5,7])
>>> s1 & s2
{3,5}
>>> s1 | s2
{1,2,3,4,5,6,7,8}