繁体   English   中英

仅在列表中查找唯一坐标

[英]Finding ONLY Unique Coordinates in List

我有一个坐标列表,比如

list_cor = 
    [[4190091.4195999987, 7410226.618699998], 
    [4190033.2124999985, 7410220.0823], 
    [4190033.2124999985, 7410220.0823], 
    [4190035.7005000003, 7410208.670500003], 
    [4190033.2124999985, 7410220.0823], 
    [4190022.768599998, 7410217.844300002]]

我只需要获得这些值:

[[4190091.4195999987, 7410226.618699998], 
[4190035.7005000003, 7410208.670500003], 
[4190022.768599998, 7410217.844300002]]

尝试numpy.unique()但它添加了这个项目[4190033.2124999985, 7410220.0823] ,我不需要。

numpy.uniqueaxisreturn_counts参数一起使用:

arr, uniq_cnt = np.unique(list_cor, axis=0, return_counts=True)
uniq_arr = arr[uniq_cnt==1]

您快到了 :

coords=[ x+1j*y for (x,y) in list_cor] # using complex; a way for grouping
uniques,counts=np.unique(coords,return_counts=True)
res=[ [x.real,x.imag] for x in uniques[counts==1] ] # ungroup

为了 :

[[4190022.7685999982, 7410217.8443000019],
 [4190035.7005000003, 7410208.6705000028],
 [4190091.4195999987, 7410226.6186999977]]

对于没有return_counts参数的旧版本 numpy,您可以使用collections.Counter帮助自己:

>>> list_cor = np.array(list_cor)  # assuming list_cor is a numpy array
>>> counts = collections.Counter(map(tuple, list_cor))
>>> counts_arr = np.array([counts[tuple(x)] for x in list_cor])
>>> list_cor[counts_arr == 1]
array([[ 4190091.4196,  7410226.6187],
       [ 4190035.7005,  7410208.6705],
       [ 4190022.7686,  7410217.8443]])

在简单的纯 python 基本类型中:

# transform to tuples
list_cor=[tuple(c) for c in list_cor]
# transform back after using set to select unique elements only
list_cor_unique=[list(l) for l in list(set(list_cor))]
# create a copy
list_cor_more_than_once = [i for i in list_cor]
# drop all the elements appearing only once
[list_cor_more_than_once.remove(tuple(l)) for l in list_cor_unique if tuple(l) in list_cor]
# finally, keep the uniques not appearing more than once
list_cor_unique=[l for l in list_cor_unique if (tuple(l) in list_cor) and (not (tuple(l) in list_cor_more_than_once)) ]

优点:

  • 没有外部库

  • 将适用于更高维度的坐标

我喜欢使用字典来跟踪计数:

>>> counts = {}
>>> for coordinate in list_cor:
...     coordinate = tuple(coordinate) # so it can be hashed and used as dict key
...     counts.setdefault(coordinate, 0) # add coordinate to dict
...     counts[coordinate] += 1 # increment count for coordinate
...

然后你有一个看起来像这样的字典:

>>> counts
{(4190091.4195999987, 7410226.618699998): 1, (4190033.2124999985, 7410220.0823): 3, (4190035.7005000003, 7410208.670500003): 1, (4190022.768599998, 7410217.844300002): 1}

然后,您可以使用列表理解来创建唯一坐标列表:

>>> [list(coordinate) for coordinate, count in counts.items() if count == 1]
[[4190091.4195999987, 7410226.618699998], [4190035.7005000003, 7410208.670500003], [4190022.768599998, 7410217.844300002]]

如果你离开罚款的坐标元组,可以更换list(coordinate)coordinate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM