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 https://dev59.com/THI95IYBdhLWcg3wyBCc#2158522
# And I need it, because output is a nested list :(
for i in outputDict:
result.append(flatten(i))
print np.array(result)
所以,这个方法可以工作,但是在处理大列表时不实用。 首先我遇到了 RuntimeError: maximum recursion depth exceeded in cmp 然后应用了 sys.setrecursionlimit(10000) 之后我又遇到了 Segmentation fault 我该如何在处理大于100000个元素的大列表时实现Eumiros的解决方案?
np.unique(map(tuple, input))
。 - Fred Foo