我正在尝试在以下列表列表中查找字母的索引:
例如:
>>> alphabet = [[["A","B","C"],["D","E","F"],["G","H","I"]],[["J","K","L"],["M","N","O"],["P","Q","R"]],[["S","T","U"],["V","W","X"],["Y","Z","_"]]]
>>> find("H",alphabet)
(0,2,1)
执行此操作的最 Pythonic 方法是什么?
最佳答案
如果你真的想要一个解决这个问题的任何深度的解决方案,这就是你正在寻找的东西(作为一个简单的递归函数):
def find_recursive(needle, haystack):
for index, item in enumerate(haystack):
if not isinstance(item, str):
try:
path = find_recursive(needle, item)
if path is not None:
return (index, ) + path
except TypeError:
pass
if needle == item:
return index,
return None
编辑:请记住,在 2.x 中,您希望 basestring
也允许使用 unicode 字符串 - 此解决方案适用于 3.x 用户。
关于python - 列表列表列表中项目的索引(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14124203/