List操作

1.創(chuàng)建List

>>> list2 = [1,2,3,4]
>>> list2
[1, 2, 3, 4]

2.Append:末尾添加元素

  • 添加單個元素
>>> list1
[1, 2, 3, 4, 5]
>>> list1.append(6)
>>> list1
[1, 2, 3, 4, 5, 6] 
  • 添加List元素
>>> list1
[1, 2, 3, 4, 5, 6]
>>> list2 = [7,8,9]
>>> list1.append(list2)
>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9]]

3.Extend:將List元素分別添加至List

>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9]]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9]

4.Count:查詢List內(nèi)某個元素的個數(shù)

>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9]
>>> list1.count(3)
1
>>> list1.append(3)
>>> list1.count(3)
2
>>> list1
[1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9, 3]

5.Insert:將某個元素插到List的某個位置

>>> list1.insert(0,0)
>>> list1
[0, 1, 2, 3, 4, 5, 6, [7, 8, 9], 7, 8, 9, 3]

6.Pop:刪除元素

  • 未傳參時默認隨機(最后一個)刪除一個元素
>>> list1
[0, 1, 2, 3, 4, 5, 6]
>>> list1.pop()
6
>>> list1.pop()
5
>>> list1.pop()
4
>>> list1
[0, 1, 2, 3]
  • 傳參是刪除該角標元素
>>> list1
[0, 1, 2, 3]
>>> list1.pop(2)
2
>>> list1
[0, 1, 3]

7.Remove:傳遞待刪除元素,如果有多個元素,默認刪除第一個

>>> list1
[1, 2, 3, 4, 5, 6, 3, 3, 3, 3]
>>> list1.remove(3)
>>> list1
[1, 2, 4, 5, 6, 3, 3, 3, 3]

8.Index:獲取列表中某個元素的索引值

>>> list1
[1, 2, 4, 5, 6, 3, 3, 3, 3]
>>> list1.index(4)
2
>>> list1[2]
4

9.Reverse:將List元素順序顛倒(不進行排序)

>>> list2
[2, 8, 4, 9, 0, 3, 1]
>>> list2.reverse()
>>> list2
[1, 3, 0, 9, 4, 8, 2]

10.Sort:對List元素進行排序

>>> list2
[1, 3, 0, 9, 4, 8, 2]
>>> list2.sort()
>>> list2
[0, 1, 2, 3, 4, 8, 9]

Sorted:不對原List進行排序,生成一個新的List

>>> a = [2,6,8,1,3,0,7,5,4]
>>> a
[2, 6, 8, 1, 3, 0, 7, 5, 4]
>>> b = sorted(a)
>>> b
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a
[2, 6, 8, 1, 3, 0, 7, 5, 4]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容