如何在多维数组中找到值的所有索引?

时间:2013-07-09 02:53:56

标签: python

如何编写一个函数来返回函数内特定值的所有索引?

例如:

arr = ["foo", ["foo", "foo", [1, "foo"]], "foo"]
getAllIndicesRecursively("foo", arr)

这应该返回“foo”的所有索引,它们是:[[0],[1,0],[1,1],[0,2,1],[2]]

1 个答案:

答案 0 :(得分:3)

不完全是您想象的输出,但是这个保留了列表的嵌套结构:

def getAllIndicesRecursively(s, l):
    r = []
    for i, v in enumerate(l):
        if isinstance(v, list):
            r += [ getAllIndicesRecursively(s, v) ]
        elif v == s: r += [ i ]
    return r

arr = ["foo", ["foo", "foo", [1, "foo"]], "foo"]
getAllIndicesRecursively("foo", arr)

输出:

[0, [0, 1, [1]], 2]

这会给出你描述的输出:

def getAllIndicesRecursively(s, l, agg=[], path=[]):
    for i, v in enumerate(l):
        if isinstance(v, list):
            getAllIndicesRecursively(s, v, agg, path + [ i ] )
        elif v == s: agg += [ path + [ i ] ]
    return agg

输出:

[[0], [1, 0], [1, 1], [1, 2, 1], [2]]