Pattern matching using python
In the code below how match the pattern after "answer" and "nonanswer" in the dictionary
opt_dict=(
{'answer1':1,
'answer14':1,
'answer13':12,
'answer11':6,
'answer5':5,
'nonanswer12':1,
'nonanswer11':1,
'nonanswer4':1,
'nonanswer5':1,})
And
if opt_dict:
for ii in opt_dict:
logging.debug(ii)
logging.debug(opt_dict[ii])
if ii in "nonanswer":
logging.debug(opt_dict[ii])
elif ii in "answer":
logging.debug("answer founddddddddddddddddddddddddddddddd")
logging.debug(opt_dict[ii])
else:
logging.debug("empty dict") 开发者_Python百科
I didn't keep all your logging, but this should work:
if opt_dict:
for key, value in opt_dict.items():
if "nonanswer" in key:
print "nonanswer", value
elif "answer" in key:
print "answer", value
else:
raise Exception( "invalid key" )
else:
print "empty dict"
I'm pretty sure you have your in
tests reversed. The data has the form answer1
, which will never be in the literal answer
. Try "answer" in ii
instead.
To be more specific, you can use the startswith
method, since all your data (at least in this example) actually starts with answer
or nonanswer
, and you might not want to match something of the form 34argleanswer
.
精彩评论