列表列表中的项目索引(Python)

时间:2013-01-02 14:59:59

标签: 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)

最恐怖的做法是什么?

3 个答案:

答案 0 :(得分:5)

如果你真的想要一个处理任何深度的解决方案,那么这就是你要寻找的东西(作为一个简单的递归函数):

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用户。

答案 1 :(得分:4)

您只需更改数据结构并使用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的位置加倍填充,因此

>>> where["U"]
(2, 0, 2)

答案 2 :(得分:3)

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)