How best to write this if-else?
Ben Wolfson
wolfson at uchicago.edu
Sat Apr 21 17:27:35 EDT 2001
In article <roy-D0E658.17013521042001 at news.panix.com>, "Roy Smith"
<roy at panix.com> wrote:
> What if I want to execute different code depending on which expression I
> matched? Something along the lines of (pseudocode):
>
> if (m = e1.match(line)):
> text1 = m.group(1)
> do_complicated_processing (text1)
> elif (m = e2.match(line)):
> text1 = m.group(1)
> text2 = m.group(2)
> print text1, text2
> elif (m = e3.match(line)):
> return
You could do
def meaningful_name_1(matchobject):
do_complicated_processing(matchobject.group(1))
def meaningful_name_2(matchobject): ...etc
re_dispatch = {re.compile(blah):meaningful_name_1,
re.compile(durh):meaningful_name_2
..etc
}
for re, func in re_dispatch.items():
m = re.match(line)
if m:
func(m)
break
else:
no match found
--
Barnabas T. Rumjuggler
Thou hast been called, O Sleep! The friend of woe,
But 'tis the happy who have called thee so.
-- Robert Southey
More information about the Python-list
mailing list