2017-10-05 21 views
1

我有一个包含一些文本数据和数字坐标列表的列表,如下所示:如何在一个列表中搜索一对坐标?

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])))任何意义。

任何人都可以帮我一把吗?

+0

'list'对象*不工作就像'numpy.ndarray'对象*。 –

+0

这个我已经明白了。任何对工作解决方案的建议? – maurobio

+2

循环播放列表,检查是否有'sub [-2] == x和sub [-1] == y' –

回答

2

利用列表理解。遍历所有坐标并查看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) 
+1

就是这样!非常感谢*。 – maurobio

1

如果你正在寻找一个简单的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)坐标匹配。

+0

也是一个简单而直接的解决方案。你在我的问题中指出的程序语句(print coords [(coords == str(x))&(coords == str(y))])显然是错误的(这就是为什么它返回给我一个空列表)。 – maurobio

1

您可以使用此非numpy的列表解析:

>>> [[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') 
+0

非numpy解决方案也很好,但它只返回第一个列表元素(并且可能有重复)。 – maurobio

+0

@maurobio它为什么只返回第一个?如果有多个元素与模式匹配,则会将它们全部返回。 –

+0

当然,我很抱歉。在运行代码之前,我仅根据您提供的示例撰写了我的评论。 – maurobio

2

对于您可以使用字典解析一个通用的解决方案,

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

请注意,如果列表中有多个匹配项,则只会返回最后一个匹配项。 –

相关问题