列表和元组的操作

列表(list)

append 向列表末尾追加

>>> a = [1, 2, 3]
>>> a.append('1')
>>> a
[1, 2, 3, '1']

insert 插入到指定下标

>>> a = [1, 2, 3]
>>> a.insert(1, '1')
>>> a
[1, '1', 2, 3]

remove

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a.remove('e')
>>> a
['s', 'h', 'e', 'p']

del

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> del a[1]
>>> a
['s', 'e', 'e', 'p']

pop 如果不传索引,默认删除最后的索引

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a.pop()
'p'
>>> a
['s', 'h', 'e', 'e']
>>> a.pop(0)
's'
>>> a
['h', 'e', 'e']

切片  左边的索引:右边的索引(:步长)

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a[:]
['s', 'h', 'e', 'e', 'p']
>>> a[-4:-1:2] ['h', 'e']

index 查指定元素的索引

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a.index('h')
1

count 查指定元素的个数

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a.count('e')
2

 

其它操作

clear 清空列表(python3)

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a.clear()
>>> a
[]

reverse 反转

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> a.reverse()
>>> a
['p', 'e', 'e', 'h', 's']

sort 排序(按照ascii排序规则)

>>> a = ['2s', '5h', 'ce', 'Be', '*p']
>>> a.sort()
>>> a
['*p', '2s', '5h', 'Be', 'ce']

extend 扩展

>>> a = ['s', 'h', 'e', 'e', 'p']
>>> b = [1, 2, 3, 4, 5]
>>> a.extend(b)
>>> a
['s', 'h', 'e', 'e', 'p', 1, 2, 3, 4, 5]
>>> b
[1, 2, 3, 4, 5]

copy (python3,浅copy,只copy一层)

>>> a = ['s', 'h', 'e', 'e', 'p', ['today', '3-11']]
>>> b = a.copy()
>>> b
['s', 'h', 'e', 'e', 'p', ['today', '3-11']]
>>> b[4] = 'e'
>>> b
['s', 'h', 'e', 'e', 'e', ['today', '3-11']]
>>> a
['s', 'h', 'e', 'e', 'p', ['today', '3-11']]
>>> b[5][0] = 'tomorrow'
>>> b
['s', 'h', 'e', 'e', 'e', ['tomorrow', '3-11']]
>>> a
['s', 'h', 'e', 'e', 'p', ['tomorrow', '3-11']]

 

元组(tuple,只读列表)

只有两个方法:index()和count()

posted @ 2018-03-11 11:40  AllenZhang_(*^▽^*)  阅读(93)  评论(0编辑  收藏  举报