雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

用于从数组中删除重复元素的 Python 程序

2024-08-17 29

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


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”运算符正在检查当前元素是否存在于空列表中。如果它不存在,则该元素将附加到结果列表中,否则忽略该元素。


使用集

Set 是 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)


参数

键 − 它是必需的参数。它需要一个可迭代对象来指定新字典的键。


值 − 它是一个可选参数,所有键的值。默认值为“无”。


在此示例中,我们将创建一个仅包含键的字典,而不使用键和值对。


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() 方法会自行删除重复的值。然后我们将其转换为列表以获取包含所有唯一元素的数组。


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

更新于:1个月前
赞一波!3

文章评论

全部评论