python - 在没有 numpy 的情况下搜索二维列表

标签 python python-3.x list function

我想定义一个接受两个参数的函数:intlist

如果函数在列表中找到整数,它会返回它的坐标

例如,如果不使用 numpy,我将如何处理以下列表中的数字 4?

l = [
         [0, 0, 0, 0, 0, 0, 0, 0, 0],
         [0, 2, 1, 1, 0, 1, 1, 1, 0],
         [0, 1, 0, 1, 0, 0, 0, 1, 0],
         [0, 1, 0, 1, 1, 1, 0, 1, 0],
         [0, 1, 0, 0, 0, 1, 0, 1, 0],
         [0, 1, 1, 1, 0, 1, 0, 1, 0],
         [0, 0, 0, 1, 0, 1, 0, 1, 0],
         [0, 1, 1, 1, 0, 1, 0, 1, 0],
         [0, 1, 0, 0, 0, 0, 0, 1, 0],
         [0, 1, 0, 1, 1, 1, 0, 1, 0],
         [0, 1, 0, 1, 0, 1, 0, 1, 0],
         [0, 1, 1, 1, 0, 1, 1, 4, 0],
         [0, 0, 0, 0, 0, 0, 0, 0, 0]
    ]

您可以假设目标总是只出现一次,并且总是包含在列表中。

最佳答案

The target will always show up only once and will always be contained in the list

您可以使用enumerate 来枚举外部列表和内部列表的元素。

def coords(lst, find):
    return next((i, j) for i, sub in enumerate(lst)
                       for j, x in enumerate(sub)
                       if x == find)

使用列表 l 进行演示:

>>> coords(l, 2)
>>> (1, 1)
>>> coords(l, 1)
>>> (1, 2)

如果您稍后想要在目标不在列表中时调整函数以正常工作,请记住 next采用可选的 default 参数。

关于python - 在没有 numpy 的情况下搜索二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084961/

相关文章:

python - ProcessPoolExecutor 日志记录失败?

python - 将 python3 可执行文件更改为另一个版本

python - 从列表中传递参数

java - 将 null 放在列表的末尾

python - 如果字符串包含重复单词,则仅保留第一个单词

python - 在 Python 中从命令行输入变量

python - 根据相关列值插入列

python - 在函数中定义字典时Python中的内存泄漏

python-3.x - 无法从部分初始化的模块 '_has_surrogates' 导入名称 'email.utils'

python - 如何在 Python 中并行检查多个列表中是否存在某个项目?