Python 从数组中删除重复元素

Python 从数组中删除重复元素

数组是由相同数据类型的元素组成的集合,数组中的每个元素通过索引值进行标识。它是一种最简单的数据结构,每个数据元素只能通过其索引号直接访问。

Python中的数组

Python没有特定的数据结构来表示数组。在这里,我们可以使用列表作为数组。

[6, 4, 1, 5, 9]
  0  1  2  3  4

在Python中,索引从0开始。在上面的块中,整数6、4、1、5、9是数组元素,而0、1、2、3、4是相应的索引值。

数组可以有重复的元素,在本文中,我们将讨论一些从数组中删除重复元素的方法。

输入输出场景

假设我们有一个包含重复值的输入数组。结果数组将只包含唯一的元素。

Input array:
A = [1, 5, 3, 6, 3, 5, 6, 1]
Output array:
[1, 5, 3, 6]

给定数组中的唯一元素是1、5、3、6。

使用For循环

我们将使用for循环来迭代所有数组元素,在每次迭代中,我们将使用not in运算符来查找重复项。

示例

在这个示例中,首先我们初始化一个空列表结果来存储在for循环中找到的所有唯一值。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = []

for i in lst: 
   if i not in result: 
      result.append(i) 

print ("The array after removing repeated elements: ", result)

输出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]

“not in” 运算符用来检查当前元素是否存在于空列表中。如果不存在,则将该元素添加到结果列表中,否则忽略该元素。

使用集合

集合是Python中的一种数据结构,用于存储唯一的数据。这意味着它不允许存储重复的元素。

示例

在这个例子中,我们将简单地将数组的数据类型从列表转换为集合的数据类型。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = list(set(lst)) 

print ("The array after removing repeated elements: ", result)

输出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 3, 5, 6]

正如我们所知,集合数据结构无法在其中保存重复项,因此我们得到的输出数组中包含所有唯一的元素。

使用 Enumerate() 函数

Enumerate() 是Python内置函数,它接受一个可迭代对象,并返回一个包含计数和从可迭代对象中迭代的值的元组。

语法

enumerate(iterable, start=0)

示例

我们将在列表解析中使用enumerate()函数来跟踪数组中每个元素的索引,然后可以使用索引值i来检查元素n是否已经存在于索引i之前的数组中。如果存在,则忽略该元素,否则将其添加到结果数组中。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array 
result = [i for i, n in enumerate(lst) if n not in lst[:i]]

print ("The array after removing repeated elements: ", result)

输出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]

使用Dict.fromkeys()

python的dict.fromkeys()方法用于从给定的键和值集合创建一个字典。字典存储一个唯一的键集。

语法

dict.fromkeys(keys, values)

参数

  • Keys − 这是一个必需的参数。它接受一个可迭代对象,指定新字典的键。

  • Values − 这是一个可选参数,所有键的值。默认值为None。

示例

在这个示例中,我们将创建一个只有键而没有键值对的字典。

lst = [1, 5, 3, 6, 3, 5, 6,  1] 
print ("The original array is: ",lst) 

# Remove repeated elements from array

result = list(dict.fromkeys(lst))

print ("The array after removing repeated elements: ", result)

输出

The original array is:  [1, 5, 3, 6, 3, 5, 6, 1]
The array after removing repeated elements:  [1, 5, 3, 6]

正如我们所知,字典中的键是不能重复的。因此,fromkeys()方法会自动删除重复的值。然后我们将它转换为列表,以获得包含所有唯一元素的数组。

这是一些可以从数组中删除重复元素的方法。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程