Python程式列印整數列表中的重複元素?


本文將展示如何從整數列表中找出重複元素。列表可以寫成方括號之間用逗號分隔的值(專案)的列表。列表的一個重要特點是,列表中的專案不必是相同型別。

假設我們有以下輸入列表:

[5, 10, 15, 10, 20, 25, 30, 20, 40]

輸出顯示重複元素:

[10, 20]

使用for迴圈列印整數列表中的重複元素

我們將使用for迴圈來顯示整數列表的重複元素。我們將迴圈遍歷並比較列表的每個元素以查詢匹配項。之後,如果找到匹配項,則意味著它是重複項,並顯示相同的元素。

示例

# Create a List myList = [5, 10, 15, 18, 20, 25, 30, 30, 40, 50, 50, 50] dupItems = [] uniqItems = {} # Display the List print("List = ",myList) for x in myList: if x not in uniqItems: uniqItems[x] = 1 else: if uniqItems[x] == 1: dupItems.append(x) uniqItems[x] += 1 print("Duplicate Elements = ",dupItems)

輸出

List =  [5, 10, 15, 18, 20, 25, 30, 30, 40, 50, 50, 50]
Duplicate Elements =  [30, 50]

使用Counter列印整數列表中的重複元素

我們將使用Counter來顯示整數列表中的重複元素。Counter來自Collections模組。此模組實現專門的容器資料型別,提供Python通用內建容器dict、list、set和tuple的替代方案。

示例

from collections import Counter # Create a List myList = [5, 10, 15, 10, 20, 25, 30, 20, 40] # Display the List print("List = ",myList) # Get the Count of each elements in the list d = Counter(myList) # Display the Duplicate elements res = list([item for item in d if d[item]>1]) print("Duplicate Elements = ",res)

輸出

List =  [5, 10, 15, 10, 20, 25, 30, 20, 40]
Duplicate Elements =  [10, 20]

使用集合列表推導式列印整數列表中的重複元素

列表推導式的語法如下:

[expression for item in list]

現在讓我們看一個例子:

示例

# Create a List myList = [5, 10, 15, 10, 20, 25, 30, 20, 40] # Display the List print("List = ",myList) # Display the duplicate elements print(list(set([a for a in myList if myList.count(a) > 1])))

輸出

List =  [5, 10, 15, 10, 20, 25, 30, 20, 40]
[10, 20]

更新於:2022年8月11日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.