python - 如何在列表中搜索一对坐标?

标签 python list search

我有一个包含一些文本数据和数字坐标的列表列表,如下:

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)

关于python - 如何在列表中搜索一对坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595337/

相关文章:

python - 在 Python 3.x 的整数列表中限制用户输入

algorithm - 定位边界2D实体

python - 如何找出/打印使用哪个版本的协议(protocol)生成了 pickle 文件

java - 成对操作给定的 Java 流

python - 为需要 kwargs 的 Callable 输入提示

python - 如何前进到嵌套列表中的下一个项目? Python

mysql - 更高级的 MySQL 记录搜索

ios - 在 ios 中实现 'search' 或排序

python - 将查询数据保存到数据帧时出错

Python3 从字典创建 3-D 图(值 : Tuple)