【发布时间】:2017-10-05 21:51:53
【问题描述】:
我有一个包含一些文本数据和数值坐标的列表,如下:
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])))。
谁能帮帮我?
【问题讨论】:
-
list对象不像numpy.ndarray对象那样工作。 -
这个我已经明白了。对可行的解决方案有何建议?
-
遍历你的列表,检查是否
sub[-2] == x and sub[-1] == y