首頁  >  文章  >  後端開發  >  Python程式刪除數組中的重複元素

Python程式刪除數組中的重複元素

王林
王林轉載
2023-09-07 11:13:021751瀏覽

Python程式刪除數組中的重複元素

陣列是相同資料類型的元素的集合,陣列中的每個元素都由索引值來識別。它是一種最簡單的資料結構,其中每個資料元素只需使用其索引號即可直接存取。

Python 中的陣列

Python 沒有特定的資料結構來表示陣列。在這裡,我們可以使用 List 一個陣列。

 [6, 4, 1, 5, 9]
  0  1  2  3  4

Python中的索引從0開始。在上面的程式碼區塊中,整數6,4,1,5,9是數組元素,0,1,2,3,4是各自的索引值。

陣列可以有重複元素,在本文中,我們將討論從陣列中刪除重複元素的幾種方法。

輸入輸出場景

假設我們有一個包含重複值的輸入陣列。並且產生的陣列將僅包含唯一元素。

Input array:
A = [1, 5, 3, 6, 3, 5, 6, 1]
Output array:
[1, 5, 3, 6]

元素 1、5、3、6 是給定陣列中的唯一元素。

使用 For 迴圈

我們將使用 for 迴圈來迭代所有陣列元素,在每次迭代中我們將使用 not in 運算子來尋找重複項。

範例

在此範例中,首先我們初始化一個空列表結果來儲存在 for 迴圈中找到的所有唯一值。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = []

for i in lst: 
   if i not in result: 
      result.append(i) 

print ("The array after removing repeated elements: ", result)

輸出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]

「not in」運算子正在檢查目前元素是否存在於空列表中。如果不存在,則將該元素追加到結果清單中,否則忽略該元素。

使用集合

Set是Python中的一種資料結構,它儲存唯一的資料。這意味著,它不允許儲存重複的元素。

範例

在此範例中,我們將簡單地將陣列從清單資料類型轉換為集合資料類型。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = list(set(lst)) 

print ("The array after removing repeated elements: ", result) 

輸出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 3, 5, 6]

眾所周知,集合資料結構中不能容納重複項,因此我們得到了包含所有唯一元素的輸出數組。

使用 Enumerate() 函數

Enumerate() 是一個 Python 內建函數,它接受一個可迭代物件並傳回一個包含計數和迭代該可迭代物件所獲得的值的元組。

文法

enumerate(iterable, start=0)

範例

我們將在列表推導式中執行 enumerate() 函數來追蹤數組中每個元素的索引,然後可以使用索引值 i 來檢查元素 n 是否已存在於數組中到索引 i。如果存在,我們將忽略該元素,否則我們會將其新增至結果陣列。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = [i for i, n in enumerate(lst) if n not in lst[:i]]

print ("The array after removing repeated elements: ", result) 

輸出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]

使用 Dict.fromkeys()

python dict.fromkeys() 方法用於根據給定的鍵和值集建立字典。字典儲存一組唯一的鍵。

文法

dict.fromkeys(keys, values)

參數

  • Keys - 這是必要的參數。它需要一個迭代來指定新字典的鍵。

  • Values - 它是一個可選參數,所有鍵的值。預設值為“無”。

範例

在此範例中,我們將建立一個僅包含鍵的字典,而不包含鍵和值對。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array
 
result = list(dict.fromkeys(lst))

print ("The array after removing repeated elements: ", result) 

輸出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]

眾所周知,字典中的鍵是不能重複的。因此, fromkeys() 方法會自行刪除重複的值。然後我們將其轉換為列表以獲取包含所有唯一元素的陣列。

這些是我們可以從陣列中刪除重複元素的一些方法。

以上是Python程式刪除數組中的重複元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除