Movatterモバイル変換
[0]ホーム
How best to write this if-else?
Alex Martellialeaxit at yahoo.com
Sat Apr 21 18:21:04 EDT 2001
"Ben Wolfson" <wolfson at uchicago.edu> wrote in messagenews:dWmE6.638$E4.25725 at uchinews...> 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)): [snip]> re_dispatch = {re.compile(blah):meaningful_name_1,> re.compile(durh):meaningful_name_2> ..etc> }> for re, func in re_dispatch.items():Dictionaries have no guaranteed order, so, if the linecan match more than one re, it will be 'random' whichone gets matched. In general, you're better off witha sequence of pairs, where you control the order:re_dispatch = ( (re.compile(blah), meaningful_name_1), (re.compile(durh), meaningful_name_2))for re, func in re_dispatch:Here you don't really need the dictionary's functionalityanyway, just a sequence of re->function pairs, so youmight as well use it even when order of re attempted isnot significant (it often is -- if not for correctness, aswhen more than one re may match, then maybe forspeed, as trying likely-matching and/or simpler re's firstmay make things faster).Alex
More information about the Python-listmailing list
[8]ページ先頭