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