|
操作
|
列表
|
|
方法
|
示例
|
|
增加
|
list.append(obj)
增加元素到末尾
|
eg.
>>> list1=['hello','world','how','are','you']
>>> list1.append('!')
>>> list1
['hello', 'world', 'how', 'are', 'you', '!']
|
|
list.insert(index, obj)
增加元素到指定位置
index:索引位置
obj:内容
|
eg.
>>> list1
['hello', 'world', 'how', 'are', 'you', '!']
>>> list1.insert(1,',')
>>> list1
['hello', ',', 'world', 'how', 'are', 'you', '!']
|
|
list.extend(list_i)
将list_i列表中的元素增加到list中
|
eg.
>>> list
['hello', 'how', 'are', 'you']
>>> list.extend(['good','girl'])
>>> list
['hello', 'how', 'are', 'you', 'good', 'girl']
|
|
删除
|
list.pop():
默认删除list末尾的元素
list.pop(index)
删除指定位置的元素,index是索引
|
eg.
>>> list1
['hello', ',', 'world', 'how', 'are', 'you', '!']
>>> list1.pop()
'!'
>>> list1.pop(1)
','
|
|
del list[index]
删除指定位置的元素,index是索引
del list
删除整个列表
|
eg.
>>> list1
['hello', 'world', 'how', 'are', 'you']
>>> del list1[1]
>>> list1
['hello', 'how', 'are', 'you']
>>> list1
['hello', 'how', 'are', 'you']
>>> del list1
>>> list1
Traceback (most recent call last):
File "<stdin>", line
1, in <module>
NameError: name 'list1' is not defined
|
|
list.remove(obj)
移除列表第一个与obj相等的元素
|
eg.
>>> list=['hello', 'world', 'how', 'are', 'you']
>>> list.remove('world')
>>> list
['hello', 'how', 'are', 'you']
|
|
list.clear()
清空列表全部内容
|
eg.
>>> list=['hello', 'world', 'how', 'are', 'you']
>>> list.clear()
>>> list
[]
|
|
修改
|
list[index]=obj
修改指定位置的元素
|
eg.
>>> list1
['hello', 'world', 'how', 'are', 'you']
>>> list1[0]='hi'
>>> list1
['hi', 'world', 'how', 'are', 'you']
|
|
查询
|
list[index]
通过下标索引,从0开始
|
eg.
>>> list=['hello', 'world', 'how', 'are', 'you']
>>> list[2]
'how'
|
|
list[a:b]
切片,顾头不顾尾
|
eg.
>>> list=['hello', 'world', 'how', 'are', 'you']
>>> list[0:3]
['hello', 'world', 'how']
>>> list[1:]
['world', 'how', 'are', 'you']
>>> list[:3]
['hello', 'world', 'how']
>>> list[:]
['hello', 'world', 'how', 'are', 'you']
|