[Tutor] how to do multiple searching against many lists
Kent Johnson
kent37 at tds.net
Thu Jan 19 19:37:40 CET 2006
Srinivas Iyyer wrote:
> Hi Group,
>
> my Problem:
>
> I have soms list for variety of animals, birds,
> bacteria
>
>
> I have another list:
> search_list =
> ['cat','python','parrot','donkey','e.coli']
>
> animals = ['cat','tiger','donkey','zebra','lemur']
> birs = ['parrot','mina','oriole','blue jay']
> bacteria =
> ['e.coli','bacillus','staphy','acetobacter']
>
> my output should look like this:
>
> cat '\t' animal
> python '\t' animal
> parrot '\t' bird
> donkey '\t'animal
> e.coli '\t' bacteria
>
> Can I do this using dictionaries , so that to make it
> faster?
I would make animals, birds and bacteria into sets rather than dicts
since the values don't map to anything. You could store the sets in a
single dict to give you the name -> set mapping. For example:
>>> animals = set(['cat','tiger','donkey','zebra','lemur'])
>>> birds = set(['parrot','mina','oriole','blue jay'])
>>> bacteria = set(['e.coli','bacillus','staphy','acetobacter'])
>>> fauna = { 'animals' : animals, 'birds' : birds, 'bacteria' :
bacteria }
>>> for item in ['cat','python','parrot','donkey','e.coli']:
... for setName, setValue in fauna.iteritems():
... if item in setValue:
... print '%s\t%s' % (item, setName)
...
cat animals
parrot birds
donkey animals
e.coli bacteria
Or, if each critter can be in only one set, you could make one dict that
maps the critter name to the set it is in, and just do one lookup:
>>> fauna2 = {}
>>> for animal in animals: fauna2[animal] = 'animal'
...
>>> for bird in birds: fauna2[bird] = 'bird'
...
>>> for bacterium in bacteria: fauna2[bacterium] = 'bacteria'
...
>>> for item in ['cat','python','parrot','donkey','e.coli']:
... print '%s\t%s' % (item, fauna2.get(item, 'None'))
...
cat animal
python None
parrot bird
donkey animal
e.coli bacteria
Kent
More information about the Tutor
mailing list