簡體   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