【发布时间】: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