編寫一個 Python 程序,從給定的列表中刪除所有重複項。Python 集合不允許重複,所以我們可以將列錶轉換為集合,然後將其轉換回列表將刪除列表重複。
# Remove Duplicates from List
dupList = [1, 2, 3, 2, 4, 8, 9, 1, 7, 6, 4, 5]
print("List Items = ", dupList)
uniqSet = set(dupList)
uniqList = list(uniqSet)
print("List Items after removing Duplicates = ", uniqList)
Python 使用設置輸出 移除列表中的重複項
List Items = [1, 2, 3, 2, 4, 8, 9, 1, 7, 6, 4, 5]
List Items after removing Duplicates = [1, 2, 3, 4, 5, 6, 7, 8, 9]
從列表中刪除重複項目的 Python 程序
這個 Python 程序允許輸入列表大小和項目。for 循環將迭代雙工項。帶有 not in 運算符的 if 語句檢查該值是否不在優衣庫列表中。如果為真,則將該值追加到優衣庫列表中。
# Remove Duplicates from List
dupList = []
listNumber = int(input("Enter the Total List Items = "))
for i in range(1, listNumber + 1):
listValue = int(input("Enter the %d List Item = " %i))
dupList.append(listValue)
print("List Items = ", dupList)
uniqList = []
for val in dupList:
if val not in uniqList:
uniqList.append(val)
print("List Items after removing Duplicates = ", uniqList)
在這個例子中,我們使用 Python 列表理解從列表中移除重複的項目。這段代碼與上面的例子相同,但是我們使用了列表理解的概念。
# Remove Duplicates from List
dupList = [1, 2, 5, 8, 1, 9, 11, 5, 22, 6, 2, 8, 14]
print("List Items = ", dupList)
uniqList = []
[uniqList.append(i) for i in dupList if i not in uniqList]
print("List Items after removing Duplicates = ", uniqList)
List Items = [1, 2, 5, 8, 1, 9, 11, 5, 22, 6, 2, 8, 14]
List Items after removing Duplicates = [1, 2, 5, 8, 9, 11, 22, 6, 14]
在本例中,我們從集合中導入了 OrderedDict,並使用 fromkeys 函數刪除重複項。別忘了把結果轉換成列表。
# Remove Duplicates from List
from collections import OrderedDict
dupList = [8, 1, 9, 2, 8, 4, 9, 11, 5, 22, 6, 4, 8]
print("List Items = ", dupList)
uniqList = OrderedDict.fromkeys(dupList)
print("List Items after removing Duplicates = ", list(uniqList))
使用排序從集合輸出中刪除列表中的重複項
List Items = [8, 1, 9, 2, 8, 4, 9, 11, 5, 22, 6, 4, 8]
List Items after removing Duplicates = [8, 1, 9, 2, 4, 11, 5, 22, 6]
numpy 和pands模塊都有去除重複的獨特功能,所以我們使用了相同的功能,並將結果轉換為列表。為了轉換結果,我們使用了 tolist()函數。
# Remove Duplicates from List
import numpy as np
import pandas as pd
dupList = [1, 2, 2, 4, 1, 5, 6, 8, 6, 8, 9, 7, 4]
print("List Items = ", dupList)
uniqList = np.unique(dupList).tolist()
print("List Items after removing Duplicates = ", uniqList)
uniqList2 = pd.unique(dupList).tolist()
print("List Items after removing Duplicates = ", uniqList2)
使用 numpy 唯一功能輸出 刪除列表中的重複項
List Items = [1, 2, 2, 4, 1, 5, 6, 8, 6, 8, 9, 7, 4]
List Items after removing Duplicates = [1, 2, 4, 5, 6, 7, 8, 9]
List Items after removing Duplicates = [1, 2, 4, 5, 6, 8, 9, 7]
使用枚舉從列表中刪除重複項的 Python 程序。
# Remove Duplicates from List
from collections import OrderedDict
dupList = [1, 2, 3, 2, 4, 1, 5, 6, 5, 8, 7, 9, 8]
print("List Items = ", dupList)
uniqList = [val for x, val in enumerate(dupList) if val not in dupList[:x]]
print("List Items after removing Duplicates = ", uniqList)
使用枚舉輸出刪除列表中的重複項
List Items = [1, 2, 3, 2, 4, 1, 5, 6, 5, 8, 7, 9, 8]
List Items after removing Duplicates = [1, 2, 3, 4, 5, 6, 8, 7, 9]
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/254192.html