Python 程序如何打印整数列表中的重复项?

programmingpythonserver side programming更新于 2025/3/14 20:28:17

在本文中,我们将显示整数列表中的重复项。列表可以写为方括号之间以逗号分隔的值(项)列表。列表的重要之处在于列表中的项目不必是同一类型

假设我们有以下输入列表 -

[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]

使用计数器打印整数列表中的重复项

我们将使用计数器显示整数列表中的重复项。计数器来自 Collections 模块。此模块实现了专门的容器数据类型,为 Python 的通用内置容器、字典、列表、集合和元组提供了替代方案 -

示例

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]

相关文章


有用资源