Checking for keywords in several lists

Alex Martelli aleax at aleax.it
Thu Jan 24 06:22:22 EST 2002


"Heiko Wolf" <heiko.wolf at dlr.de> wrote in message
news:d013da35.0201240248.6b233b95 at posting.google.com...
> Hi,
>
> imagine some lists of strings like
>
> list1_words = ('word1','word2')
> list2_words = ('word3','word4')
>
> Now I want to check if string is whether in list1_words or in
> list2_words. I can do that by
>
> if string in list1_words:
>   do something
> elif string in list2_words:
>   do something else
>
> But if these lists get more, it is very uncomfortable doing it the
> if/elif -way.
> Any other suggestions?

A simple approach might be:

for function, wordlist in (
    dosomething, ('word1', 'word2', 'word3'),
    dosomethingelse, ('word4', 'word5'),
    yetanothercase, ('word6', 'word7', 'word8')):
        if theword in wordlist:
            function()
            break
else:
    # theword is in none of the lists, do
    # some default action here
        adefaultaction()

where each of dosomething, dosomethingelse, yetanothercase and
adefaultaction are functions (or other callables) written to
be called without arguments.  Not the NAMES of the functions,
mind: the function themselves.

If you do this often, it's worth encapsulating it, by doing ONCE:

myniceselector = SeveralListSelector((
    dosomething, ('word1', 'word2', 'word3'),
    dosomethingelse, ('word4', 'word5'),
    yetanothercase, ('word6', 'word7', 'word8')),
    adefaultaction)

after which you can just use
    myniceselector(theword)
and don't worry about how it's internally implemented all the time.

One way to write SeveralListSelector, for example:

class SeveralListSelector:
    def __init__(self, actions_and_lists, the_default_action):
        self.action_dictionary = {}
        for action, wordlist in actions_and_lists:
            for aword in wordlist:
                self.action_dictionary[aword] = action
        self.default_action = the_default_action
    def __call__(self, aword):
        return self.action_dictionary.get(aword, self.default_action)


Alex






More information about the Python-list mailing list