Python程式:移除陣列中重複元素


陣列是相同資料型別元素的集合,陣列中的每個元素都由索引值標識。它是最簡單的 資料結構,每個資料元素都可以僅使用其索引號直接訪問。

Python中的陣列

Python沒有專門的資料結構來表示陣列。在這裡,我們可以使用列表作為陣列。

 [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`運算子查詢重複項。

示例

在這個例子中,我們首先初始化一個空列表`result`來儲存在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`”運算子檢查當前元素是否存在於空列表中。如果不存在,則將該元素新增到`result`列表中,否則忽略該元素。

使用集合

集合是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)

引數

  • **鍵** - 這是必需引數。它接受一個指定新字典鍵的可迭代物件。

  • **值** - 這是可選引數,所有鍵的值。預設值為None。

示例

在這個例子中,我們將只建立具有鍵的字典,而不是鍵值對。

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()`方法會自動移除重複值。然後我們將其轉換為列表,以獲得包含所有唯一元素的陣列。

這些是從陣列中移除重複元素的一些方法。

更新於:2023年5月16日

瀏覽量:1000+

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告