
数组是相同数据类型的元素的集合,数组中的每个元素都由一个索引值来标识。它是一种最简单的数据结构,其中每个数据元素只需使用其索引号即可直接访问。
Python 没有特定的数据结构来表示数组。在这里,我们可以使用 List 一个数组。
[6, 4, 1, 5, 9] 0 1 2 3 4
Python中的索引从0开始。在上面的代码块中,整数6,4,1,5,9是数组元素,0,1,2,3,4是各自的索引值。
数组可以有重复元素,在本文中,我们将讨论从数组中删除重复元素的几种方法。
立即学习“Python免费学习笔记(深入)”;
假设我们有一个包含重复值的输入数组。并且生成的数组将仅包含唯一元素。
Input array: A = [1, 5, 3, 6, 3, 5, 6, 1] Output array: [1, 5, 3, 6]
元素 1、5、3、6 是给定数组中的唯一元素。
我们将使用 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() 是一个 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]
python dict.fromkeys() 方法用于根据给定的键和值集创建字典。字典存储一组唯一的键。
dict.fromkeys(keys, values)
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() 方法会自行删除重复的值。然后我们将其转换为列表以获取包含所有唯一元素的数组。
这些是我们可以从数组中删除重复元素的一些方法。
以上就是Python程序删除数组中的重复元素的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号