繁体   English   中英

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

[英]Index of item in a list of lists of lists (Python)

我试图在下面的列表列表中找到一个字母的索引:

例如:

>>> 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)

最恐怖的做法是什么?

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

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的位置加倍,以便填充

>>> 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM