In python, given a list of lists, how do you identify the index of a matching element? -


>>> birds = ['duck', 'chicken', 'goose'] >>> cats = ['tiger', 'lion'] >>> humans = ['human'] >>> at_the_zoo = [birds, cats, humans] 

given list of lists at_the_zoo, how locate list tiger in?

for animal in sum(at_the_zoo, []):     if "tiger" == animal:         print "1 help!" 

for example, can find tiger in list of animals, , if use enumerate, tell me @ index 3. how figure out part of element 1 of list at_the_zoo. searching duck tell me element 0, etc.

thanks!

i think like:

def find_element(nested_lst, what):     idx, sublst in enumerate(nested_lst):         try:             idx2 = sublst.index(what)             return (idx, idx2)         except valueerror:             pass 

should work.

example:

>>> def find_element(nested_lst, what): ...     idx, sublst in enumerate(nested_lst): ...         try: ...             idx2 = sublst.index(what) ...             return (idx, idx2) ...         except valueerror: ...             pass ...  >>> birds = ['duck', 'chicken', 'goose'] >>> cats = ['tiger', 'lion'] >>> humans = ['human'] >>> find_element([birds, cats, humans], 'human') (2, 0) >>> find_element([birds, cats, humans], 'gator')  # returns none if not found. >>> find_element([birds, cats, humans], 'tiger') (1, 0) 

it's worth noting on average, list.index o(n) operation means lists aren't efficient data structure testing membership. if actual data supports it, might worthwhile consider using set instead.


Comments

Popular posts from this blog

rdbms - what exactly the undo information lives in oracle? -

bash - How do you programmatically add a bats test? -

clojure - 'get' replacement that throws exception on not found? -