简体   繁体   中英

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

What would be an efficient and pythonic way to get the index of a nested list item?

For example:

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

How can I grab the index of 'plum'?

Try this:

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

Output:

[(1, 1)]

Simple iteration through the indices of a nested list (only for the case of two levels, though).

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

Notably this fails for the case of a list element not being a list itself.

Ie:

Input (fail case-- selected element not list):

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

Output (fail case-- selected element not list):

# Nothing!

VS

Input (lucky case-- selected element a list):

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

Output (lucky case-- selected element a list):

(2,1)

VS

Input (appropriate use case):

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

Output (appropriate use case):

(0,0)

here are some examples:

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

To manipulate your list some_list , I turned its sub-elements into string so as to handle them. Thus, if one has

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

And one wants to find the index and the sub-index of the string element 'plum'

>>> to_find = 'plum'

Then

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

would get indexes you want.

Setup

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

Solution

#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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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