Reputation: 141
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'?
Upvotes: 1
Views: 10731
Reputation: 109
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.
I.e.:
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)
Upvotes: 1
Reputation: 19947
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]
Upvotes: 0
Reputation: 6655
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.
Upvotes: 0
Reputation: 6556
Try this:
[(i, el.index("plum")) for i, el in enumerate(some_list) if "plum" in el]
Output:
[(1, 1)]
Upvotes: 3
Reputation: 1532
here are some examples:
apple = some_list[0][0]
plum = some_list[1][1]
kiwi = some_list[2][0]
Upvotes: -1