1. 程式人生 > 實用技巧 >python 列表の常用操作

python 列表の常用操作

確定列表的長度: 方法len() len(A_list)

在列表中新增元素:

(1)在列表末尾新增元素:方法append() A_list.append(strB)

(2)在列表中插入元素:方法inert() A_list.insert(index,strB)

(insert()方法:在索引index處插入strB,其他的元素統一後移(注意索引不要越界))

在列表中刪除元素:

(1)使用del刪除元素 del A_list[index] (刪除A_list列表中索引index處的元素)

(2)使用方法pop()刪除元素 A_list.pop(index) (刪除A_list列表中索引index處的元素並返回,若index為空則刪除並返回列表末尾元素)

注:方法pop()可使用變數接收刪除並返回的元素,而del則不可。

(3)根據值刪除元素 A_list.remove(strB) (刪除A_list列表中值為strB的元素)

注:方法remove()只刪除第一個指定的值。

對列表中元素進行排序:

(1)方法sort()對列表進行永久性排序:

A_list.sort() (預設按照首字母大小順序排序)

A_list.sort(reverse = True) :按照首字母大小的相反順序排序。

(2)函式sorted()對列表進行臨時排序:

sorted(A_list)

反轉列表:

方法reverse() :A_list.reverse() (永久性的修改,再呼叫方法reverse()即可恢復)

注: (1)索引為 -1 為列表最後一個元素(前提是列表長度大於0);