【发布时间】:2015-05-19 15:40:15
【问题描述】:
问题是,我如何才能完全删除数组中多次出现的元素。在下面,您会看到一种在处理更大数组时非常缓慢的方法。 有什么想法可以用 numpy 的方式来做吗?提前致谢。
import numpy as np
count = 0
result = []
input = np.array([[1,1], [1,1], [2,3], [4,5], [1,1]]) # array with points [x, y]
# count appearance of elements with same x and y coordinate
# append to result if element appears just once
for i in input:
for j in input:
if (j[0] == i [0]) and (j[1] == i[1]):
count += 1
if count == 1:
result.append(i)
count = 0
print np.array(result)
更新:因为以前过于简单化
再次明确:如何从数组/列表中删除与某个属性有关的多次出现的元素?这里:列出长度为 6 的元素,如果每个元素的第一个和第二个条目都在列表中出现多次,则从列表中删除所有相关元素。希望我不会混淆。 Eumiro 在这方面帮助了我很多,但我没有设法将输出列表展平:(
import numpy as np
import collections
input = [[1,1,3,5,6,6],[1,1,4,4,5,6],[1,3,4,5,6,7],[3,4,6,7,7,6],[1,1,4,6,88,7],[3,3,3,3,3,3],[456,6,5,343,435,5]]
# here, from input there should be removed input[0], input[1] and input[4] because
# first and second entry appears more than once in the list, got it? :)
d = {}
for a in input:
d.setdefault(tuple(a[:2]), []).append(a[2:])
outputDict = [list(k)+list(v) for k,v in d.iteritems() if len(v) == 1 ]
result = []
def flatten(x):
if isinstance(x, collections.Iterable):
return [a for i in x for a in flatten(i)]
else:
return [x]
# I took flatten(x) from http://stackoverflow.com/a/2158522/1132378
# And I need it, because output is a nested list :(
for i in outputDict:
result.append(flatten(i))
print np.array(result)
所以,这行得通,但是对于大列表是不切实际的。 首先我得到 RuntimeError:在 cmp 中超出最大递归深度 并且申请后 sys.setrecursionlimit(10000) 我有 分段故障 如何为大于 100000 个元素的大列表实施 Eumiros 解决方案?
【问题讨论】:
标签: python arrays numpy duplicates