操作 |
列表 |
方法 |
樣本 |
增加 |
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‘] |