繁体   English   中英

如何获取嵌套列表项的索引?

[英]How can I get the index of a nested list item?

什么是获取嵌套列表项索引的有效且pythonic方法?

例如:

some_list = [ [apple, pear, grape], [orange, plum], [kiwi, pineapple] ]

如何获取“李子”的索引?

尝试这个:

[(i, el.index("plum")) for i, el in enumerate(some_list) if "plum" in el]

输出:

[(1, 1)]

通过嵌套列表的索引进行简单迭代(不过仅适用于两个级别的情况)。

def findelm(element, list):
    x = 0 
    while x < len(list):
        y = 0
        while y < len(list[x]):
            if list[x][y] == element: print "({},{})".format(x,y)
            y = y + 1
        x = x + 1

值得注意的是,如果列表元素不是列表本身,则失败。

即:

输入(失败情况-所选元素未列出):

list = ["hey", "ho", ["hi", "haha", "help"], "hooha"]
findelm("hey", list)

输出(失败情况-所选元素未列出):

# Nothing!

VS

输入(幸运的情况-选定元素为列表):

list = ["hey", "ho", ["hi", "haha", "help"], "hooha"]
findelm("haha", list)

输出(幸运的情况-选定元素为列表):

(2,1)

VS

输入(适当的用例):

list = [["hey"], ["ho"], ["hi", "haha", "help"], ["hooha"]]
findelm("hey", list)

输出(适当的用例):

(0,0)

这里有些例子:

apple = some_list[0][0]
plum = some_list[1][1]
kiwi = some_list[2][0]

为了操纵您的列表some_list ,我将其子元素转换为字符串以便处理它们。 因此,如果有

>>> some_list = [
        ['apple', 'pear', 'grape'], 
        ['orange', 'plum'],
        ['kiwi', 'pineapple']
    ]

并且想要找到字符串元素'plum'的索引和子索引

>>> to_find = 'plum'

然后

>>> [(index_,sub_list.index(to_find))\
     for index_, sub_list in enumerate(some_list)\
     if to_find in sub_list]
[(1, 1)]

将获得您想要的索引。

设定

a = [ ['apple', 'pear', 'grape'], ['orange', 'plum'], ['kiwi', 'pineapple'] ]
Out[57]: [['apple', 'pear', 'grape'], ['orange', 'plum'], ['kiwi', 'pineapple']]

#Iterate the list of lists and build a list of dicts and then merge the dicts into one dict with words as keys and their index as values.

dict(sum([{j:[k,i] for i,j in enumerate(v)}.items() for k,v in enumerate(a)],[])).get('plum')
Out[58]: [1, 1]

dict(sum([{j:[k,i] for i,j in enumerate(v)}.items() for k,v in enumerate(a)],[])).get('apple')
Out[59]: [0, 0]

暂无
暂无

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

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