從 Python 列表中去除重複子串


有時,我們可能需要透過消除列表中的重複元素來最佳化給定的列表。這可以透過使用 Python 標準庫中提供的多種方法組合來實現。

帶 set 和 split

split 方法可用於隔離用於重複檢查的元素,set 方法用於儲存分離列表元素中的唯一元素。

示例

# initializing list
listA = [ 'xy-xy', 'pq-qr', 'xp-xp-xp', 'dd-ee']

print("Given list : ",listA)

# using set() and split()
res = [set(sub.split('-')) for sub in listA]

# Result
print("List after duplicate removal : " ,res)

輸出

執行以上程式碼會得到以下結果 −

Given list : ['xy-xy', 'pq-qr', 'xp-xp-xp', 'dd-ee']
List after duplicate removal : [{'xy'}, {'pq', 'qr'}, {'xp'}, {'ee', 'dd'}]

帶列表

我們還可以使用列表方法,並使用 for 迴圈配合使用,以便僅在分離後從列表中捕獲唯一元素。

示例

# initializing list
listA = [ 'xy-xy', 'pq-qr', 'xp-xp-xp', 'dd-ee']

print("Given list : ",listA)

# using list
res = list({i for sub in listA for i in sub.split('-')})

# Result
print("List after duplicate removal : " , res)

輸出

執行以上程式碼會得到以下結果 −

Given list : ['xy-xy', 'pq-qr', 'xp-xp-xp', 'dd-ee']
List after duplicate removal : ['dd', 'pq', 'ee', 'xp', 'xy', 'qr']

更新於: 2020-08-26

299 瀏覽

啟動你的 職業之旅

完成課程後獲得認證

開始
廣告