Python - 在 n 维列表中查找所有项目 x 的位置

标签 python recursion multidimensional-array

如何找出所有项目 x 在任意形状或大小的 n 维列表中的位置? (示例:[1, 2, [3, [1]]...])

这是我为找到第一项而想出的代码:(未经过严格测试)

def where(x, inputList):
    return _where(x, inputList, [])
def _where(value, inputList, dimension):
    if isinstance(inputList, list):
        i = 0
        for l in inputList:
            dimension.append(i)
            D = _where(value, l, dimension)
            if not D == None:
                return D
            i += 1
            del dimension[-1]
        return None
    else:
        if value == inputList:
            return dimension
        else:
            return None

它递归地检查列表中的每个项目,当它找到正确的项目时,它返回该项目的维度或坐标

所需的输入/输出示例:

x = 1
inputlist = [1, [2, 21], [1]]
o = where_All(x, inputlist)
# o is [[0], [2, 0]]
print inputlist[0]    # is 1
print inputlist[2][0] # is 1

O 是列表中每个项目的坐标列表,它等于 x

最佳答案

如果我没理解错的话,您想在嵌套数组中查找元素的坐标。然后你可以使用下面的函数,它更简单并且利用了 yield 这在输入 (haystack) 本身是一个迭代器时特别有用(例如,当从文件中读取时或类似):

def where(needle, haystack, indexes=[]):
    for i, el in enumerate(haystack):
        if type(el) == list:
            for res in where(needle, el, indexes + [i]):
                yield res 
        elif el == needle:
            yield(indexes + [i])

a = [1, 2, [3, [1]]]
for coords in where(1, a):
    print(coords)

结果:

[0]
[2, 1, 0]

关于Python - 在 n 维列表中查找所有项目 x 的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42041009/

相关文章:

c++ - 如何 std::sort 一个 3 维 vector

php - 如何从数组中提取特定字段

javascript - 在 jupyter 笔记本中加载外部 javascript 库

python - 选定时间范围内的真实值

python - django rest 框架 - 使用 detail_route 和 detail_list

c# - 在 .NET 中使用哪些类/命名空间进行图像处理?

python - 如何将元组列表转换为以索引为键的字典

math - 求解递归关系T(n)=√nT(√n)+ n

C 方法应该调用自己递归两次,但似乎没有这样做

java - Fibonacci(n) 的这个实现是如何工作的? [递归]