Har*_*E-W 4 python list python-2.7
我试图在下面的列表列表中找到一个字母的索引:
例如:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
最恐怖的做法是什么?
如果你真的想要一个处理任何深度的解决方案,这就是你要寻找的东西(作为一个简单的递归函数):
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
Run Code Online (Sandbox Code Playgroud)
编辑:记住,在2.x中,你想要basestring允许unicode字符串 - 这个解决方案对于3.x用户来说很好.