# 在 Python 中從列表中刪除重複項

Sahil Bhosale 2023年1月30日

Python 中的列表是一個資料結構，用於以特定的順序儲存資料。列表可以儲存多種型別的資料，即 int、float、字串、另一個列表等。列表是可突變的，這意味著一旦建立的值可以在以後改變。它用方括號 `[]` 表示。

``````myList = [2, 1, 2, 3, 0, 6, 7, 6, 4, 8]
print(myList)
``````

``````[2, 1, 2, 3, 0, 6, 7, 6, 4, 8]
``````

``````myList = [2, 1, 2, 3, 0, 6, 7, 6, 4, 8]

resultantList = []

for element in myList:
if element not in resultantList:
resultantList.append(element)

print(resultantList)
``````

``````[2, 1, 3, 0, 6, 7, 4, 8]
``````

1. 如果你不想在刪除重複元素後還保持列表內元素的順序，那麼你可以使用 `Set` 資料結構。
2. 如果你想在刪除重複元素後保持列表內元素的順序，那麼你可以使用名 `OrderedDict`

## 使用 Python 中的 `set()` 函式從列表中刪除重複元素

``````mySet = {80, 10, 50, 18, 3, 50, 8, 18, 9, 8}
print(mySet)
``````

``````{3, 8, 9, 10, 80, 18, 50}
``````

``````original_list = [80, 10, 50, 18, 3, 50, 8, 18, 9, 8]

print("Original List is: ", original_list)

convert_list_to_set = set(original_list)
print("Set is: ", convert_list_to_set)

new_list = list(convert_list_to_set)
print("Resultant List is: ", new_list)

original_list = list(convert_list_to_set)
print("Removed duplicates from original list: ", original_list)
``````

``````Original List is:  [80, 10, 50, 18, 3, 50, 8, 18, 9, 8]
Set is:  {3, 8, 9, 10, 80, 18, 50}
Resultant List is:  [3, 8, 9, 10, 80, 18, 50]
Removed duplicates from original list:  [3, 8, 9, 10, 80, 18, 50]
``````

## 在 Python 中使用 `OrderDict` 來刪除重複的內容並維持列表的順序

``````from collections import OrderedDict

myList = [2, 1, 2, 3, 0, 6, 7, 6, 8, 0, 4, 8]

final_list = list(OrderedDict.fromkeys(myList))

print(final_list)
``````

``````[2, 1, 3, 0, 6, 7, 8, 4]
``````

Sahil is a full-stack developer who loves to build software. He likes to share his knowledge by writing technical articles and helping clients by working with them as freelance software engineer and technical writer on Upwork.