我正在尝试在以下列表列表中查找字母的索引:
例如:
>>> 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 方式是什么?
我正在尝试在以下列表列表中查找字母的索引:
例如:
>>> 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 用户。
您可以简单地更改数据结构并使用dict
:
>>> import itertools
>>> import string
>>> lets = string.ascii_uppercase
>>> where = dict(zip(lets, itertools.product(range(3), repeat=3)))
>>> where
{'A': (0, 0, 0), 'C': (0, 0, 2), 'B': (0, 0, 1), 'E': (0, 1, 1), 'D': (0, 1, 0), 'G': (0, 2, 0), 'F': (0, 1, 2), 'I': (0, 2, 2), 'H': (0, 2, 1), 'K': (1, 0, 1), 'J': (1, 0, 0), 'M': (1, 1, 0), 'L': (1, 0, 2), 'O': (1, 1, 2), 'N': (1, 1, 1), 'Q': (1, 2, 1), 'P': (1, 2, 0), 'S': (2, 0, 0), 'R': (1, 2, 2), 'U': (2, 0, 2), 'T': (2, 0, 1), 'W': (2, 1, 1), 'V': (2, 1, 0), 'Y': (2, 2, 0), 'X': (2, 1, 2), 'Z': (2, 2, 1)}
>>> where["H"]
(0, 2, 1)
但请注意,我不会将U
to pad 的位置加倍,所以
>>> where["U"]
(2, 0, 2)
In [9]: def find(val,lis):
ind=[(j,i,k) for j,x in enumerate(lis) for i,y in enumerate(x) \
for k,z in enumerate(y) if z==val]
return ind[0] if ind else None
...:
In [10]: find("H",alphabet)
Out[10]: (0, 2, 1)
In [14]: find("M",alphabet)
Out[14]: (1, 1, 0)