List操作

1.創(chuàng)建List

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

2.Append:末尾添加元素

  • 添加單個(gè)元素
>>> 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)某個(gè)元素的個(gè)數(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:將某個(gè)元素插到List的某個(gè)位置

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

6.Pop:刪除元素

  • 未傳參時(shí)默認(rèn)隨機(jī)(最后一個(gè))刪除一個(gè)元素
>>> list1
[0, 1, 2, 3, 4, 5, 6]
>>> list1.pop()
6
>>> list1.pop()
5
>>> list1.pop()
4
>>> list1
[0, 1, 2, 3]
  • 傳參是刪除該角標(biāo)元素
>>> list1
[0, 1, 2, 3]
>>> list1.pop(2)
2
>>> list1
[0, 1, 3]

7.Remove:傳遞待刪除元素,如果有多個(gè)元素,默認(rèn)刪除第一個(gè)

>>> 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:獲取列表中某個(gè)元素的索引值

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

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

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

10.Sort:對(duì)List元素進(jìn)行排序

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

Sorted:不對(duì)原List進(jìn)行排序,生成一個(gè)新的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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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