Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, get index from list of lists

I have a list of lists of strings, like this:

l = [['apple','banana','kiwi'],['chair','table','spoon']]

Given a string, I want its index in l. Experimenting with numpy, this is what I ended up with:

import numpy as np
l = [['apple','banana','kiwi'],['chair','table','spoon']]
def ind(s):
    i = [i for i in range(len(l)) if np.argwhere(np.array(l[i]) == s)][0]
    j = np.argwhere(np.array(l[i]) == s)[0][0]
    return i, j
s = ['apple','banana','kiwi','chair','table','spoon']
for val in s:
    try:
        print val, ind(val)
    except IndexError:
        print 'oops'

This fails for apple and chair, getting an indexerror. Also, this just looks bad to me. Is there some better approch to doing this?

like image 713
user2258896 Avatar asked Apr 08 '13 18:04

user2258896


People also ask

How do you get the index of a list in a list of lists in Python?

The simplest and most Pythonic way that finds the row and column indices in a general list of lists, is to use a nested for loop and the built-in enumerate() function to iterate over the elements and indices at the same time.

How do I get a list of elements in a list in Python?

Access Elements in a List of Lists in Python. We can access the contents of a list using the list index. In a flat list or 1-d list, we can directly access the list elements using the index of the elements.


1 Answers

Returns a list of tuples containing (outer list index, inner list index), designed such that the item you're looking for can be in multiple inner lists:

l = [['apple','banana','kiwi'],['chair','table','spoon']]
def findItem(theList, item):
   return [(ind, theList[ind].index(item)) for ind in xrange(len(theList)) if item in theList[ind]]

findItem(l, 'apple') # [(0, 0)]
findItem(l, 'spoon') # [(1, 2)]
like image 127
Manny D Avatar answered Sep 26 '22 03:09

Manny D