如何删除 Python 数组中的重复值?
How do you remove duplicate values in array in Python?
我有一个数组,其中每个元素都是一组随机数的平均值。我希望能够删除此数组中的重复值。我该怎么做?
到目前为止我已经尝试过:
for i in range(len(array)):
for j in array:
if array[i] == j:
然后进行一些操作以从数组中删除元素。但是,这只会删除每个重复元素的每个实例。
您可能需要考虑使用 python set
:)
代码示例:
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list: what you want
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
然后你可以使用remove
或discard
(如果你不想在删除non-existing项时出错):
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
如果您更喜欢使用列表,则可以使用 list
函数转换回列表:
my_list = list(my_set)
文档:https://python-reference.readthedocs.io/en/latest/docs/sets/
您可以尝试创建一个集合的数组:
deduplicated_array = list(set(array))
您可以简单地使用 np.unique():
unique_values = np.unique(array)
如果你不关心元素的顺序,那么使用下面的
deduplicated = list(set(array))
这种方式对我有用 (Ways to remove duplicates from list):
res = []
[res.append(x) for x in test_list if x not in res]
# printing list after removal
print ("The list after removing duplicates : " + str(res))
我有一个数组,其中每个元素都是一组随机数的平均值。我希望能够删除此数组中的重复值。我该怎么做?
到目前为止我已经尝试过:
for i in range(len(array)):
for j in array:
if array[i] == j:
然后进行一些操作以从数组中删除元素。但是,这只会删除每个重复元素的每个实例。
您可能需要考虑使用 python set
:)
代码示例:
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list: what you want
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
然后你可以使用remove
或discard
(如果你不想在删除non-existing项时出错):
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# remove an element
# not present in my_set
# you will get an error.
# Output: KeyError
my_set.remove(2)
如果您更喜欢使用列表,则可以使用 list
函数转换回列表:
my_list = list(my_set)
文档:https://python-reference.readthedocs.io/en/latest/docs/sets/
您可以尝试创建一个集合的数组:
deduplicated_array = list(set(array))
您可以简单地使用 np.unique():
unique_values = np.unique(array)
如果你不关心元素的顺序,那么使用下面的
deduplicated = list(set(array))
这种方式对我有用 (Ways to remove duplicates from list):
res = []
[res.append(x) for x in test_list if x not in res]
# printing list after removal
print ("The list after removing duplicates : " + str(res))