Checking for keywords in several lists
Steve Holden
sholden at holdenweb.com
Thu Jan 24 10:11:38 EST 2002
"Heiko Wolf" <heiko.wolf at dlr.de> wrote in message
news:d013da35.0201240629.2e4af237 at posting.google.com...
> "Alex Martelli" <aleax at aleax.it> wrote in message
news:<a2oqpc$77q$1 at serv1.iunet.it>...
> >> "Heiko Wolf" <heiko.wolf at dlr.de> wrote in message
> >> news:d013da35.0201240248.6b233b95 at posting.google.com...
> >> 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.
> >
>
> I tried your approach, but it hit me with a TypeError.
>
> for function, wordlist in (
> TypeError: unpack non-sequence
>
> What am I doing wrong?
>
Alex meant this:
for function, wordlist in (
(dosomething, ('word1', 'word2', 'word3')),
(dosomethingelse, ('word4', 'word5')),
(yetanothercase, ('word6', 'word7', 'word8'))):
if theword in wordlist:
function()
break
...
Without the extra parentheses, the structure of the tuple you are iterating
over is unsuitable for two-element assignments. You will also need to define
dosomething, dosomethingelse and yetanothercase as functions before the code
will execute, of course.
regards
Steve
--
Consulting, training, speaking: http://www.holdenweb.com/
Python Web Programming: http://pydish.holdenweb.com/pwp/
More information about the Python-list
mailing list