Python – 刪除指定索引元素後的列表列印


Python 語言是處理資料最強大的程式語言之一。列表是 Python 中多種資料結構型別的一種。列表可以容納不同型別的資料物件,例如整數、字串甚至浮點數。一旦賦值給列表的值之後,就不能再更改。列表中的元素使用索引值來標識,本文將討論透過指定索引刪除元素的方法。

刪除指定索引元素後的列表列印

列表由元素組成,索引值從 0 開始到元素數量減一。從列表中刪除元素可以用圖示來解釋。刪除元素有多種方法。下面的列表包含 7 個元素,第一行表示元素的索引值,第二行包含元素的值。

刪除索引“3”處的元素

要刪除元素,我們需要找到列表陣列的第三個索引,即“56”。刪除該元素後,新的列表如下所示:

方法

  • 方法 1 - 使用 pop() 函式

  • 方法 2 - 使用 numpy 模組

  • 方法 3 - 使用 reduce 方法

方法 1:使用 pop() 函式刪除指定索引元素後列印列表的 Python 程式

上述方法只需使用 pop() 函式即可從列表中刪除元素。下面的程式碼可以使用 del() 函式替換 pop() 函式來刪除元素。對於 remove() 方法,透過直接將元素作為函式引數來刪除元素。

演算法

  • 步驟 1 - 建立一個列表來同時儲存整數、字串和浮點值,並將其賦值給名為 list1 的變數。

  • 步驟 2 - 使用 pop() 函式刪除索引為 2 和 0 的元素。

  • 步驟 3 - 最後,print 函式返回新的列表。

示例

#initializing the list with set of elements
list1 = [10, 20, 30, 'Hello ', 67.9]
#The pop function will simply remove the element for the mentioned index value
#index value of 2 and 0 needs to be removed
list1.pop(2)
list1.pop(0)
#print function will return the list after removing the elements.
print(list1)

輸出

[20, 'Hello ', 67.9]

方法 2:使用 numpy 模組刪除指定索引元素後列印列表的 Python 程式

當資料集較小時,可以使用簡單的方法刪除元素;當資料集較大時,我們可以切換到相應模組的內建函式。在本例中,使用 numpy 模組。

演算法

  • 步驟 1 - 宣告用於刪除元素的必需模組 numpy 為 “np”。

  • 步驟 2 - 建立包含整數、字串和浮點數的資料結構列表。

  • 步驟 3 - 要使用 numpy 模組刪除元素,需要將給定的列表轉換為 numpy 陣列。

  • 步驟 4 - 將轉換後的 numpy 陣列儲存在名為“val”的變數中。

  • 步驟 5 - 使用函式 np.delete() 在指定索引值的情況下從 numpy 陣列中刪除元素。

  • 步驟 6 - 然後將上述函式宣告為新的變數並列印新的列表。

示例

#importing the module as np
import numpy as np
#Creating a list to hold values of different data types
list1 = [10, 20, 30, 'Hello ', 67.9]
#To convert the list data structure to numpy array and stored in val
val = np.array(list1)
#The given index value elements are removed.
#The delete function has two parameters 
newlist = np.delete(val, [0,2])
#Then finally returns the new list
print(newlist)

輸出

['20' 'Hello ' '67.9']

方法 3:使用 reduce 方法刪除指定索引元素後列印列表的 Python 程式

使用 functools 模組中 reduce 函式從列表中刪除元素。

演算法

  • 步驟 1 - 從 functools 模組匯入 reduce 方法。

  • 步驟 2 - 建立一個包含元素的列表。

  • 步驟 3 - 使用 lambda 函式,這是一個無需定義的匿名函式。

  • 步驟 4 - print 語句返回刪除索引 0 和 2 元素後的列表。

示例

#importing the module
from functools import reduce
#Creating a list to hold values of different data types
list1 = [10, 20, 30, 'Hello ', 67.9]
#The elements removed using reduce method with key parameters.
new_list = reduce(lambda a,b: a+[b] if list1.index(b) not in [0,2] else a, list1, [])
#Then finally returns the new list
print(new_list)

輸出

[20, 'Hello ', 67.9]

結論

組織機構必須處理大型資料集,因此刪除不需要的元素可以提高效率並簡化工作。藉助 Python 語言,可以使用 del、remove、pop、numpy 模組和 functools 模組從列表中刪除元素。

更新於:2023年9月4日

瀏覽量 360

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.