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]
使用Set和列表推导式从整数列表中打印出重复项
列表推导式的语法如下所示−
[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]