Python list列表的使用(增删改查)
生活随笔
收集整理的這篇文章主要介紹了
Python list列表的使用(增删改查)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一.增加(append、insert)
- 二.刪除(del、remove、pop)
- 三.修改(index)
- 四.查找(len、index)
一.增加(append、insert)
1.可以增加不同數據類型的數據
#代碼如下:lists = [1,2,3,'你好',2] print('追加之前',lists) lists.append([666,'csdn']) lists.append(99) print('追加之后',lists)#運行結果:追加之前 [1, 2, 3, '你好', 2] 追加之后 [1, 2, 3, '你好', 2, [666, 'csdn'], 99]2.根據下標插入
#代碼如下:lists = [1,2,3,'你好',2] print('追加之前',lists) lists.insert(1,'插入的') print('追加之后',lists)#運行結果:追加之前 [1, 2, 3, '你好', 2] 追加之后 [1, '插入的', 2, 3, '你好', 2]二.刪除(del、remove、pop)
1.刪除單個數據/刪除指定下標的元素
#代碼如下:lists = [1,2,3,'你好',2] print('刪除之前',lists) del lists[0]#刪除單項 print('刪除之后',lists)#運行結果:刪除之前 [1, 2, 3, '你好', 2] 刪除之后 [2, 3, '你好', 2]2.刪除多項數據
#代碼如下:lists = [1,2,3,'你好',2] print('刪除之前',lists) del lists[1:3]#刪除多項 print('刪除之后',lists)#運行結果:刪除之前 [1, 2, 3, '你好', 2] 刪除之后 [1, '你好', 2]3.刪除指定的元素
#代碼如下:lists = [1,2,3,'你好',2] print('刪除之前',lists) lists.remove(3)#移除指定的元素 print('刪除之后',lists)#運行結果:刪除之前 [1, 2, 3, '你好', 2] 刪除之后 [1, 2, '你好', 2]4.使用pop刪除指定下標的元素
python #代碼如下:lists = [1,2,3,'你好',2] print('刪除之前',lists) lists.pop(0)#移除指定下標中的元素 print('刪除之后',lists)#運行結果:刪除之前 [1, 2, 3, '你好', 2] 刪除之后 [2, 3, '你好', 2]三.修改(index)
1.修改指定下標的元素
python #代碼如下:lists = [1,2,3,'你好',2] print('修改之前',lists) lists[0] = 'xyz' print('修改之后',lists)#運行結果:修改之前 [1, 2, 3, '你好', 2] 修改之后 ['xyz', 2, 3, '你好', 2]四.查找(len、index)
1.查詢列表的長度
python #代碼如下:lists = [1,2,3,'你好',2] print(len(lists))#輸出列表的長度#運行結果:52.輸出完整的列表
python #代碼如下:lists = [1,2,3,'你好',2] print(lists)#運行結果:[1, 2, 3, '你好', 2]3.獲取單個數據項
python #代碼如下:lists = [1,2,3,'你好',2] print(lists[3])#運行結果:你好4.從第二個獲取到第三個元素
python #代碼如下:lists = [1,2,3,'你好',2] print(lists[1:3])#運行結果:[2, 3]5.從第三個元素到最后所有元素
python #代碼如下:lists = [1,2,3,'你好',2] print(lists[2:])#運行結果:[3, '你好', 2]6.倒序輸出列表
python #代碼如下:lists = [1,2,3,'你好',2] print(lists[::-1])#運行結果:[2, '你好', 3, 2, 1]7.輸出兩次列表中的數據【復制】
python #代碼如下:lists = [1,2,3,'你好',2] print(lists*2)#運行結果:[1, 2, 3, '你好', 2, 1, 2, 3, '你好', 2]8.index查找該元素第一次出現時的下標
python #代碼如下:lists = [1,2,3,'你好',2] print(lists.index(2))#運行結果:19.在2-5號下標不包括5號下標中查找元素2
python #代碼如下:lists = [1,2,3,'你好',2] print(lists.index(2,2,5))#運行結果:4總結
以上是生活随笔為你收集整理的Python list列表的使用(增删改查)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 切片的简单讲解
- 下一篇: Python 字典类型的使用