【问题标题】:Python - Finding location of all items x in n-dimensional listPython - 在n维列表中查找所有项目x的位置
【发布时间】:2017-06-21 19:32:34
【问题描述】:

如何找出所有项目 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

【问题讨论】:

  • 请在您的问题中给出期望的输入/输出。你的代码给出错误的答案吗?如果您的代码正常工作,您可能想改为在 codereview 上提问。
  • 看看this answer。它可以处理嵌套列表和字典的任意组合,并且可以找到所有匹配项,而不仅仅是第一个。如果您不需要处理字典,您可以轻松地简化代码。
  • @wizzup Jökull 想要在嵌套列表中找到 所有 个匹配项。当前代码只找到第一个。
  • 考虑使用numpy.where() Documentation
  • @UpSampler 我尝试使用 numpy.where() 但它只处理非常严格的结构化列表,如 [[1, 2], [3, 4]] 我希望它处理非结构化列表,如[1, [2, 3, [1]], [1, 3]]

标签: python recursion multidimensional-array


【解决方案1】:

如果我理解正确,您想在嵌套数组中查找元素的坐标。然后,您可以使用以下更简单的函数并利用 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]

【讨论】:

  • “yield from”似乎在我目前使用的 2.7 中不起作用
  • 我重写了python 2的答案
  • 看看答案,它使用了许多您可能不知道的python功能,例如为您增加i值的枚举,因此您不需要i+=1等。 type(el) 也比 isinstance 更适合非类
  • 非常感谢,我会这样做的
  • 我猜你的解决方案也可以使用yield 而不是return。它的作用是,当它被称为迭代器 (for i in where..) 时,yield “返回”该值,但在下一次调用时,您可以在您停止的函数中继续执行
猜你喜欢
  • 2011-08-03
  • 1970-01-01
  • 2013-08-05
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
相关资源
最近更新 更多