i learning python , need advice regarding searching items in list. have list contains list of lists. how can search item in list , return value same list example below.
example: mylist = [['red', 'tomato'], ['green', 'pear'], ['red', 'strawberry'], ['yellow', 'lemon']] word = 'green' return pear
is possible find first instance or n-th instance in list well?
first_instance = 'red' return tomato last_instance = 'red' return strawberry
you can use collections.defaultdict
:
using once dictionary created it'll take o(1) lookup find instance of "red" or other color.
>>> mylist = [['red', 'tomato'], ['green', 'pear'], ['red', 'strawberry'], ['yellow', 'lemon']] >>> collections import defaultdict >>> dic = defaultdict(list) >>> k,v in mylist: dic[k].append(v) ... >>> dic['red'][0] #first instance 'tomato' >>> dic['red'][-1] #last instance 'strawberry' >>> dic["yellow"][0] #first instance of yellow 'lemon'
define simple function here handle index errors:
>>> def solve(n, color, dic): try: return dic[color][n] except indexerror: return "error: {0} has {1} instances".format(color,len(dic[color])) ... >>> dic = defaultdict(list) >>> k,v in mylist: dic[k].append(v) ... >>> solve(0, "red", dic) 'tomato' >>> solve(-1, "red", dic) 'strawberry' >>> solve(0, "yellow", dic) 'lemon' >>> solve(1, "yellow", dic) 'error: yellow has 1 instances'
Comments
Post a Comment