簡體   English   中英

如何在列表中搜索一對坐標?

[英]How to search a list for a pair of coordinates?

我有一個包含一些文本數據和數字坐標的列表列表,如下所示:

coords = [['1a', 'sp1', '1', '9'],
          ['1b', 'sp1', '3', '11'],
          ['1c', 'sp1', '6', '12'],
          ['2a', 'sp2', '1', '9'],
          ['2b', 'sp2', '1', '10'],
          ['2c', 'sp2', '3', '10'],
          ['2d', 'sp2', '4', '11'],
          ['2e', 'sp2', '5', '12'],
          ['2f', 'sp2', '6', '12'],
          ['3a', 'sp3', '4', '13'],
          ['3b', 'sp3', '5', '11'],
          ['3c', 'sp3', '8', '8'],
          ['4a', 'sp4', '4', '12'],
          ['4b', 'sp4', '6', '11'],
          ['4c', 'sp4', '7', '8'],
          ['5a', 'sp5', '8', '8'],
          ['5b', 'sp5', '7', '6'],
          ['5c', 'sp5', '8', '2'],
          ['6a', 'sp6', '8', '8'],
          ['6b', 'sp6', '7', '5'],
          ['6c', 'sp6', '8', '3']]

給定一對坐標(x,y),我想在列表中找到元素(其本身就是一個列表),該元素對應於所述一對坐標。 因此,例如,如果我有x = 5且y = 12,我將得到['2e', 'sp2', '5', '12']

我嘗試了這個:

x = 5
y = 12
print coords[(coords == str(x)) & (coords == str(y))]

但有一個空列表。

我也試過這個:

import numpy as np    
print np.where(coords == str(x)) and np.where(coords == str(y))

但對返回的內容毫無意義((array([ 2, 7, 8, 12]), array([3, 3, 3, 3])))

有人可以幫我嗎?

利用列表理解。 遍歷所有坐標,並查看x和y相等的地方。

coords = [['1a', 'sp1', '1', '9'], ['1b', 'sp1', '3', '11'], ['1c', 'sp1', '6', '12'], ['2a', 'sp2', '1', '9'], ['2b', 'sp2', '1', '10'], ['2c', 'sp2', '3', '10'], ['2d', 'sp2', '4', '11'], ['2e', 'sp2', '5', '12'], ['2f', 'sp2', '6', '12'], ['3a', 'sp3', '4', '13'], ['3b', 'sp3', '5', '11'], ['3c', 'sp3', '8', '8'], ['4a', 'sp4', '4', '12'], ['4b', 'sp4', '6', '11'], ['4c', 'sp4', '7', '8'], ['5a', 'sp5', '8', '8'], ['5b', 'sp5', '7', '6'], ['5c', 'sp5', '8', '2'], ['6a', 'sp6', '8', '8'], ['6b', 'sp6', '7', '5'], ['6c', 'sp6', '8', '3']]

x = 5
y = 12

answer = [cood for cood in coords if int(cood[2]) == x and int(cood[3]) == y]
print(answer)

對於一般的解決方案,您可以使用字典理解,

x, y = 5, 12
print({tuple(coord[-2:]):coord for coord in coords}[str(x),str(y)])

如果您正在尋找簡單的Python解決方案,請嘗試使用此方法

[coord for coord in coords if coord[2] == str(x) and coord[3] == str(y) ]

這確實使您返回[['2e', 'sp2', '5', '12']]

我不確定您要在解決方案中完成什么print coords[(coords == str(x)) & (coords == str(y))] 您需要遍歷列表以查找哪些元素與(x, y)坐標相匹配。

您可以使用以下非數字列表理解:

>>> [[a,b,c,d] for (a,b,c,d) in coords if int(c) == x and int(d) == y]
[['2e', 'sp2', '5', '12']]

使用numpy ,您應該只將第三和第四列與xy ,而不是整個行,然后采用這些索引。

>>> arr = np.array(coords)
>>> arr[(arr[:,2] == str(x)) & (arr[:,3] == str(y))]
array([['2e', 'sp2', '5', '12']], dtype='|S3')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM